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: