如何使用DropDownList.text进行选择
我正在开发一个Asp.NET项目,我正在尝试使用text属性设置下拉列表的选定值。 例如,我有一个带有文本test
的下拉列表中的项目。 以编程方式我可以通过Text
将其设置为selecteditem
吗? 我正在使用以下代码,但无法正常工作。
protected void Page_Load(object sender, EventArgs e) { string t = "test"; drpFunction.Text = t; }
但是没有用。 有什么建议 ?
string t = "test"; drpFunction.ClearSelection(); drpFunction.Items.FindByText(t).Selected = true;
设置itm.Selected = true; 仅在你首先使用drp.ClearSelection()时才有效。 我更喜欢以下内容:
drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value;
drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value;
这是选择文本的更好方法。 按照ioden的方式,它会显示错误
“无法在DropDownList中选择多个项目”
此链接可能会帮助您
public static void SelectText(this DropDownList bob, string text) { try { if (bob.SelectedIndex >= 0) bob.Items[bob.SelectedIndex].Selected = false; bob.Items.FindByText(text).Selected = true; } catch { throw new GenericDropDownListException("value", text); } }
我认为SelectedValue属性应该做你需要的。
这适用于Web
ListItem li=new ListItem(); li.Text="Stringxyz"; li.Value="Stringxyz"; // Create object of item first and find its index. DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(li);
这也很好。
protected void Page_Load(object sender, EventArgs e) { string t = "test"; drpFunction.SelectedValue = t; }
SelectedValue属性可用于通过使用项目的值设置列表控件中的项目。 但是,如果所选值与下拉列表中的值列表不匹配,则在回发期间将抛出exception。
用这个…
protected void Page_Load(object sender, EventArgs e) { string t = "test"; drpFunction.SelectedItem.Text = t; }
要么
protected void Page_Load(object sender, EventArgs e) { string t = "test"; drpFunction.SelectedItem.Value = t; }
这是正确的方法…….
string t = "test"; drpFunction.ClearSelection(); drpFunction.Items.FindByText(t).Selected = true;