第一种方法:
string ConnString = ConfigurationSettings.AppSettings["ConnectionString"];
//创建一个SqlConnection
SqlConnection Conn = new SqlConnection( ConnString );
string SQL_Select = "select id, ItemName from DDLItem order by id desc";
//构造一个SqlDataAdapter
SqlDataAdapter myAdapter = new SqlDataAdapter( SQL_Select, Conn);
//开始读取数据
Conn.Open();
DataSet dataSet = new DataSet();
myAdapter.Fill( dataSet,"Table1" );
Conn.Close();
//开始绑定DropDownList
//指定DropDownList使用的数据源
DropDownList1.DataSource = dataSet.Tables["Table1"].DefaultView;
//指定DropDownList使用的表里的那些字段
DropDownList1.DataTextField = "ItemName"; //dropdownlist的Text的字段
DropDownList1.DataValueField = "id";//dropdownlist的Value的字段
DropDownList1.DataBind();
第二种方法:
con.Open();
SqlCommand cmd = new SqlCommand(strSql,con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(new ListItem(dr["status"].ToString(), dr["status_Id"].ToString()));
}
在gridview等控件中绑定dropdownlist的简单方法
<asp:TemplateField HeaderText="是否锁定">
<ItemTemplate>
<asp:DropDownList ID="isLock" runat="server" SelectedValue=<%# Bind("cateIsLock") %>>
<asp:ListItem Text="是" Value="True"></asp:ListItem>
<asp:ListItem Text="否" Value="False"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>