C# 设置下拉列表选定索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15539841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:06:49  来源:igfitidea点击:

Setting dropdownlist selected index

c#asp.netdrop-down-menu

提问by whoadityanawandar

I have a dropdownlist with country names in alphabetical order. I want the dropdown to have (show) India as the default value always. 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...

不起作用...

回答by Civa

Select Index after DataBind(). Data Bind Binds Items in 'ddlCountryCode.Items' So you can Select index of 'india' one items exists with ddlCountryCode.

在 DataBind() 之后选择 Index。数据绑定绑定“ddlCountryCode.Items”中的项目,因此您可以选择“印度”的索引,其中一项存在于 ddlCountryCode。

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)"));

回答by ????

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


编程方式设置下拉列表 selecteditem

Edit 1

编辑 1

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)"));

回答by Pratik Mehta

DropDownList1.SelectedValue = "India";