how to select with DropDownList.text

2020-02-23 04:39发布

I am working on an Asp.NET project and I am trying to set the selected value of a dropdown list with a text property. For example i have i.e an item in the dropdown list with text test. Programmatically can i set it to selecteditem by Text?. I am using the follwing code but is not working.

protected void Page_Load(object sender, EventArgs e)
{
    string t = "test";
    drpFunction.Text = t; 
}

But is not working. Any suggestions ?

9条回答
手持菜刀,她持情操
2楼-- · 2020-02-23 05:12

Use this...

protected void Page_Load(object sender, EventArgs e)
{
    string t = "test";
    drpFunction.SelectedItem.Text = t;
}

or

protected void Page_Load(object sender, EventArgs e)
{
    string t = "test";
    drpFunction.SelectedItem.Value = t;
}

this is proper way.......

查看更多
仙女界的扛把子
3楼-- · 2020-02-23 05:12
string t = "test";
drpFunction.ClearSelection();
drpFunction.Items.FindByText(t).Selected = true;
查看更多
Evening l夕情丶
4楼-- · 2020-02-23 05:17

This Link might help you

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);
    }
}
查看更多
冷血范
5楼-- · 2020-02-23 05:19

This works in 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);

This also works fine.

查看更多
▲ chillily
6楼-- · 2020-02-23 05:20
 string t = "test";
 drpFunction.ClearSelection();
 drpFunction.Items.FindByText(t).Selected = true;
查看更多
可以哭但决不认输i
7楼-- · 2020-02-23 05:26
protected void Page_Load(object sender, EventArgs e)
{
    string t = "test";
    drpFunction.SelectedValue = t;
}

The SelectedValue property can be used to select an item in the list control by setting it with the value of the item. However, an exception will be thrown during postback if the the selected value doesn't match the list of values in the dropdown list.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx

查看更多
登录 后发表回答