从数据库更新下拉列表的代码

本文关键字:代码 下拉列表 更新 数据库 | 更新日期: 2023-09-27 18:13:22

在答案中找到从数据库更新下拉列表的代码。请告知是否有更好的替代方法。

从数据库更新下拉列表的代码

<asp:DropDownList ID="DropDownList1" runat="server" 
                         DataSource = '<%# Status %>'
                         DataTextField  = "status">
                         </asp:DropDownList>
protected DataTable Status
    {
        get
        {
             DataTable dt  = new DataTable();
            using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                string fetch_qry = @"select status from table";
                con.Open();
                using (SqlDataAdapter adpt = new SqlDataAdapter(fetch_qry, con))
                {
                    adpt.Fill(dt);                    
                }
            }
                return dt;
        }
    }

重要提示:这只会在如下方式调用DataBind函数时起作用:

protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList1.DataBind();
    }

this.DataBind();也可以,但是它将绑定页面中的所有控件。具体一点比较好。

也可以在代码页而不是设计页声明DataSource和DataTextField,如下所示:
protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList1.DataSource = Status;
        DropDownList1.DataTextField = "status";
        DropDownList1.DataBind();
    }

如果下拉列表出现在网格视图中;gridview级别的DataBind函数将绑定数据网格中存在的下拉列表中的数据:GridView1.DataBind();