根据其他选定的下拉列表项更改一个下拉列表数据

本文关键字:下拉列表 数据 一个 其他 | 更新日期: 2023-09-27 18:26:40

我的web应用程序项目中有两个下拉列表和DB。在数据库中,我有域表和子域表。在子域表中,我有域表中列DomainId的外键。我用域中的数据填充第一个下拉列表(im使用DomainId作为数据值,DomainName作为数据文本/这里是代码:

protected void Page_Load(object sender, EventArgs e)
    {
        string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
        conn = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand("SELECT DomainId , DomainName FROM Domain",conn);
        conn.Open();
        DropDownList1.DataTextField = "DomainName";
        DropDownList1.DataValueField = "DomainId";
        DropDownList1.DataSource = cmd.ExecuteReader();
        DropDownList1.DataBind();
    }

现在,当用户从下拉列表中选择项目时,我想根据所选的项目填充第二个下拉列表,但不起作用。这是代码的第二部分:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
        conn = new SqlConnection(connString);

        SqlCommand cmd = new SqlCommand("SELECT SubDomainName, SubDomainId FROM SubDomain where DomainId= @id", conn);
        cmd.Parameters.AddWithValue("@id", DropDownList1.SelectedValue);
        conn.Open();
        DropDownList2.DataTextField = "SubDomainName";
        DropDownList2.DataValueField = "SubDomainId";
        DropDownList2.DataSource = cmd.ExecuteReader();
        DropDownList2.DataBind();
        conn.Close();

    }

根据其他选定的下拉列表项更改一个下拉列表数据

将DropDownList1控件的AutoPostBack属性设置为true。如果您已经设置了,但仍然有错误,请将.aspx文件也发布为