[英]Insert into ListBox from a Database
問題:如何從數據庫中將項目插入列表框?
這是我嘗試過的:
public void Fetch()
{
using (SqlConnection cn = new SqlConnection(UtilObj.ConnectionString()))
{
cn.Open();
ExecuteFetch(cn);
cn.Close();
}
}
public void ExecuteFetch(SqlConnection cn)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "spName";
cm.Parameters.AddWithValue("@Param1", Param1Val);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
myListBox.Items.Add(dr["Color"].ToString());
}
}
}
}
即使我在調試器中填充代碼,這也會顯示一個空列表。
ASPX頁面
<asp:ListBox ID="myListBox" runat="server" />
我認為您正在尋找這樣的東西:
執行您的sp后獲取閱讀器對象
SqlDataReader reader = cmd.ExecuteReader();
myListBox.DataSource= reader; //reader object
myListBox.DataTextField = "Color"; // the field you want to show in listbox
myListBox.DataValueField = "Color"; // the value filed behind the items.
myListBox.Databind();
如果需要,文本字段和值字段也可以相同
而已。 與將項目綁定到下拉列表的方法相同。 剛在我們最近的項目中使用過
希望對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.