如何将DropDown列表绑定到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 = "";
答案 0 :(得分:1)
首先找到下拉控件。
DropDownList ddlStatus = default(DropDownList);
ddlStatus = (DropDownList)FindControl("DropDownList1");
//database connection, etc.
ddlStatus.DataSource = dt;
ddlStatus.SelectedValue = "";
答案 1 :(得分:0)
好吧,当你不知道你的控件名称(dropDown列表)时,你可以使用类似的东西:
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
}