Problem
For past few days I have been facing a problem while dynamically making a list item selected. Here is the code that I have used.
Code
ASPX <asp:DropDownList ID="DropDownList1" runat="server" Width="150px"> <asp:ListItem Value="0" Text="-- Select --" Selected="True"/> <asp:ListItem Value="1" Text="Red" /> <asp:ListItem Value="2" Text="Greeen" /> <asp:ListItem Value="3" Text="Yellow" /> <asp:ListItem Value="4" Text="Pink" /> <asp:ListItem Value="5" Text="-- All --" /> </asp:DropDownList> C# protected void Page_Load(object sender, EventArgs e) { ListItem item = DropDownList1.Items.FindByValue("5"); if (item != null) item.Selected = true; }
However, the code generates the following exception:
1. Just add the following codes before calling FindByValue() or FindByText() protected void Page_Load(object sender, EventArgs e) { DropDownList1.ClearSelection(); // New code added ListItem item = DropDownList1.Items.FindByValue("5"); if (item != null) item.Selected = true; } 2. Also the following code works fine protected void Page_Load(object sender, EventArgs e) { DropDownList1.SelectedIndex = 5; }
I hope this helps and saves your time. Happy coding