Search code examples
c#asp.netwebformsdropdown

Can't set dropdown list selected item


I have a DropDown list on an ASP.Net web page. I'm trying to set its SelectedValue` on page load. I'm using this page as a reference. Here's my code:

<asp:DropDownList runat="server" ID="ddlType" DataSourceID="sdsType" DataTextField="Name" DataValueField="AssetTypeID" />
<asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        if (Request.QueryString["searchtype"] != null)
        {
            ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
            ddlType.SelectedValue = "1";
        }
    }
    else
    {

    }
}

The first line that sets the SelectedValue will give me a Null Reference Exception and if I inspect the ddlType it has no Items. However, if I comment out the first line setting the SelectedValue and set it using the second line (just hard coding the value) it works. What's going on?


Solution

  • You can use the OnDataBound event to do your current logic

    /*Note the addition of "OnDataBound" */
    <asp:DropDownList runat="server" 
                      ID="ddlType" 
                      DataSourceID="sdsType" 
                      DataTextField="Name" 
                      DataValueField="AssetTypeID"
                      OnDataBound="ddlType_DataBound"                 
    />
    <asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />
    
    protected void ddlType_DataBound(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            if (Request.QueryString["searchtype"] != null)
            {
                ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
                ddlType.SelectedValue = "1";
            }
        }
        else
        {
    
        }
    }