[英]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.