Search code examples
c#sqlasp.netrepeatertemplatefield

Cascading DropDownList within an ItemTemplate ASP.NET C#


I am trying to create a cascading dropdownlist in my ASP.NET C# web application. What's supposed to happen is that when the first dropdownlist selected index is changed, it calls the code below and then it populates the second dropdownlist with new values. Problem is that both dropdownlists are coming up as null when I try to populate the second dropdownlist. Seems like the controls aren't being found when I search for them. They are populating on the page load with the correct information inside the ItemTemplateField of the Repeater. How do I have the cascading dropdownlists without Javascript and only C# within the Repeater? Any help is much appreciated. The code below crashes on the line that says ddl2.Items.Clear();

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) 
{
  DropDownList ddl = (DropDownList) NameRepeater.FindControl("ddlCountry");
  DropDownList ddl2 = (DropDownList) NameRepeater.FindControl("ddlState");
  ddl2.Items.Clear();
  using(SqlConnection conn = new SqlConnection(connString)) 
  {
    using(SqlCommand cmd = new SqlCommand()) 
    {
      cmd.CommandText = "SELECT State, StateID FROM States WHERE CountryID = " + ddl.SelectedValue;
      cmd.Connection = conn;
      conn.Open();
      using(SqlDataReader sdr = cmd.ExecuteReader()) 
      {
        while (sdr.Read()) 
        {
          ListItem _listStates = new ListItem();
          _listStates.Text = sdr["State"].ToString();
          _listStates.Value = sdr["StateID"].ToString();
          ddl2.Items.Add(_listStates);
        }
      }
    }
  }
  ddl2.AppendDataBoundItems = true;
  ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
  ddl2.SelectedIndex = -1;

}

Solution

  • Don't forget to call DataBind(), it is needed after you populate the dropdown:

    ddl2.DataBind();
    

    EDIT:

    DropDownList ddl = (DropDownList)NameRepeater.Items[0].FindControl("ddlCountry");
    DropDownList ddl2 = (DropDownList)NameRepeater.Items[0].FindControl("ddlState");