没有更新下拉列表更改值asp.net C#

时间:2018-01-22 05:57:40

标签: c# html asp.net

我想从下拉列表中选择值来更新另一个下拉列表。数据绑定正在起作用。但选择项目时," ddl1"的选定值不会改变。因此" ddl1.SelectedValue" notworkin正确

请检查此代码&帮我纠正它

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    conn.Open();
    string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
    SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
    DataTable dt = new DataTable();
    comm.Fill(dt);
    conn.Close();
    ddl1.DataSource = dt;

    ddl1.DataTextField = "title";
    ddl1.DataValueField = "id";
    ddl1.DataBind();
    ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
    Label2.Text = ddl1.SelectedIndex.ToString();



protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    conn.Open();
    string selectmap2 = "select [id]+' - '+[title] as title, id from map where id !='"+ddl1.SelectedValue+"' order by id;";
    SqlDataAdapter comm2 = new SqlDataAdapter(selectmap2, conn);
    DataTable dt2 = new DataTable();
    comm2.Fill(dt2);
    ddl2.DataSource = dt2;

    ddl2.DataTextField = "title";
    ddl2.DataValueField = "id";
    ddl2.DataBind();
    ddl2.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
}

ASPX:

<asp:DropDownList ID="ddl1" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="ddl1_SelectedIndexChanged"></asp:DropDownList>

1 个答案:

答案 0 :(得分:0)

protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            Populateddl1();
        }
    }
    private void Populateddl1()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        conn.Open();
        string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
        SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
        DataTable dt = new DataTable();
        comm.Fill(dt);
        conn.Close();
        ddl1.DataSource = dt;

        ddl1.DataTextField = "title";
        ddl1.DataValueField = "id";
        ddl1.DataBind();
        ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));

    }

    protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Write here for populating second dropdown code
    }