We take pride in your success. We let our positivity drive us, day in and out. Talk to us at Mindfire to know us more.

Software Technology Tips

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:
palash-httpException
 
 
 

Solution

    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 :)


Related Tags:

ASP.NET, DropDownList, Exception

Author: Palash Mondal

top

ASP.NET

Let us Connect!

privacy

copyright (c) Mindfire Solutions 2007-2012. Login