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 ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
string t = "test"; drpFunction.ClearSelection(); drpFunction.Items.FindByText(t).Selected = true;
Method 2
Setting the itm.Selected = true; only works if you drp.ClearSelection() first.
I prefer the following:
drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value;
Method 3
drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value;
This is better way to select text. By ioden’s way it will show an error
“Multiple Items Cannot be selected in DropDownList”
Method 4
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);
}
}
Method 5
I think the SelectedValue property should do what you need.
Method 6
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.
Method 7
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…….
Method 8
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0