dropdownlist动态数据绑定

第一步先上页面上托一个dropdownlist控件

前台

< asp:DropDownList ID = " DropDownList1 " runat = " server " >

</ asp:DropDownList >

后台

先写一个返回dataset的方法

/// <summary>
/// 绑定dropdownlist信息
/// </summary>
/// <returns></returns>
public DataSet Drop()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ " learning " ].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText
= " select ExamName from ExamMain group by ExamName order by ExamName " ;
SqlDataAdapter adapter
= new SqlDataAdapter(cmd);
DataSet ds
= new DataSet();
adapter.Fill(ds);
return ds;
}
}
}

调用绑定方法

public void DataDropDownList()
{
// 数据源

this .DropDownList1.DataSource = Drop();
// 要绑定的字段
this .DropDownList1.DataValueField = Drop().Tables[ 0 ].Columns[ " ExamName " ].ColumnName;
// 显示的值
this .DropDownList1.DataTextField = Drop().Tables[ 0 ].Columns[ " ExamName " ].ColumnName;
this .DropDownList1.DataBind();
}

你可能感兴趣的:(list)