我需要帮助使用数据源绑定下拉列表?

时间:2018-03-08 04:15:22

标签: asp.net

1 个答案:

答案 0 :(得分:0)

这很简单使用c#和linq。

试试这段代码。

<asp:DropDownList ID="ddlstate" CssClass="form-control" runat="server" OnSelectedIndexChanged="ddlstate_SelectedIndexChanged" AutoPostBack="true" ClientIDMode="Static">
                            </asp:DropDownList>

  <asp:DropDownList ID="ddldistric" CssClass="form-control" runat="server" ClientIDMode="Static">
                                <asp:ListItem Value="0">-Select District-</asp:ListItem>
                            </asp:DropDownList>

 protected void ddlstate_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                get_Distric(Convert.ToInt32(ddlstate.SelectedValue));
            }
            catch (Exception ex)
            {

            }
        }



public void get_Distric(Int32 stateid)
        {
            try
            {
                var qry = (db.MasterDistrics.Where(s => s.Status == 1 && s.StateID == stateid).Select(a => new { a.ID, a.Name })).ToList();

                ddldistric.DataSource = qry;
                ddldistric.DataTextField = "Name";
                ddldistric.DataValueField = "ID";
                ddldistric.DataBind();
                ddldistric.Items.Insert(0, new ListItem("--- Select District ---", "0"));
            }
            catch (Exception ex)
            {

            }

        }