[英]Setting dropdownlist selected index
I have a dropdownlist with country names in alphabetical order. 我有一个按字母顺序排列国名的下拉列表。 I want the dropdown to have (show) India as the default value always. 我希望下拉列表始终将(显示)India作为默认值。 I don't want to set the selected index with a constant because other countries may be added to the list later. 我不想将所选索引设置为常量,因为稍后可能会将其他国家/地区添加到列表中。 How can set the index to "India"? 如何将索引设置为“印度”?
ddlCountryCode.DataSource = ds1.Tables["AUser"];
ddlCountryCode.DataTextField = "CountryCode";
ddlCountryCode.SelectedIndex =
ddlCountryCode.Items.IndexOf(ddlCountryCode.Items.FindByText("India(+91)"));
ddlCountryCode.DataBind();
doesnt work... 不起作用......
You can use like this 你可以像这样使用
DropdownList1.SelectedIndex =
DropdownList1.Items.IndexOf(DropdownList1.Items.FindByValue(strText));
or 要么
DropdownList1.SelectedIndex =
DropdownList1.Items.IndexOf(DropdownList1.Items.FindByText(strText));
References 参考
Setting dropdownlist selecteditem programmatically 以编程方式设置下拉列表选项
Change the sequence of your code 更改代码的顺序
ddlCountryCode.DataSource = ds1.Tables["AUser"];
ddlCountryCode.DataTextField = "CountryCode";
ddlCountryCode.DataBind();
ddlCountryCode.SelectedIndex =
ddlCountryCode.Items.IndexOf(ddlCountryCode.Items.FindByText("India(+91)"));
DropDownList1.SelectedValue = "India";
Select Index after DataBind(). 在DataBind()之后选择Index。 Data Bind Binds Items in 'ddlCountryCode.Items' So you can Select index of 'india' one items exists with ddlCountryCode. 数据绑定绑定'ddlCountryCode.Items'中的项目因此您可以使用ddlCountryCode选择一个项目存在的'india'索引。
DropdownList1.Items is a list so u can use IndexOf()
ddlCountryCode.DataSource = ds1.Tables["AUser"];
ddlCountryCode.DataTextField = "CountryCode";
ddlCountryCode.DataBind();
ddlCountryCode.SelectedIndex =
ddlCountryCode.Items.IndexOf(ddlCountryCode.Items.FindByText("India(+91)"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.