在ItemTemplate ASP.NET C#中级联DropDownList

时间:2016-01-08 22:17:44

标签: c# sql asp.net repeater templatefield

我正在尝试在ASP.NET C#Web应用程序中创建级联下拉列表。应该发生的是当第一个下拉列表选择的索引被更改时,它调用下面的代码,然后用新值填充第二个下拉列表。问题是当我尝试填充第二个下拉列表时,两个下拉列表都将显示为null。好像我搜索时没有找到控件。它们使用Repeater的ItemTemplateField中的正确信息填充页面加载。如何在没有Javascript的情况下使用级联下拉列表,在Repeater中只有C#?任何帮助深表感谢。以下代码在显示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;

}

1 个答案:

答案 0 :(得分:1)

不要忘记拨打DataBind(),填写下拉列表后需要它:

ddl2.DataBind();

编辑:

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