在c#中绑定一个下拉列表到SQL表

本文关键字:下拉列表 一个 SQL 绑定 | 更新日期: 2023-09-27 18:18:37

如何在c#中绑定下拉列表到SQL server表

这是我目前为止的代码:

string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = @"select Epic, Company from Company ";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet dataSet1 = new DataSet();
da.Fill(dataSet1, "Company");
DataTable dt = dataSet1.Tables["Company"];
DropDownList1.DataSource = dt;
DropDownList1.SelectedValue = "";

在c#中绑定一个下拉列表到SQL表

首先找到下拉控件

DropDownList ddlStatus = default(DropDownList);
ddlStatus = (DropDownList)FindControl("DropDownList1");
//database connection, etc.
ddlStatus.DataSource = dt;
ddlStatus.SelectedValue = "";

嗯,当你不知道你的控件(下拉列表)的名称时,你可以使用类似的东西:

try
{
    //Add this couple of lines If you are adding controls dynamically and you need to find a specific control (by name)
    //--->DropDownList ddl = default(DropDownList);
    //--->ddl = (DropDownList)FindControl("DropDownList1");
    System.Data.DataTable subjects = new System.Data.DataTable();
    System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT Id, Name FROM yourTable", "your connection");
    adapter.Fill(subjects);
    DropDownList1.DataSource = subjects;
    DropDownList1.DataTextField = "Name";
    DropDownList1.DataValueField = "id";
    DropDownList1.DataBind();
}
catch (Exception ex)
{
       // Handle the error
}
相关文章: