简体   繁体   English

从数据库插入到列表框

[英]Insert into ListBox from a Database

Question: How can I insert items into a listbox from a database? 问题:如何从数据库中将项目插入列表框?

Here is what I tried: 这是我尝试过的:

    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());
                }
            }
        }
    }

This shows an empty list when I run the code even though it populates in debugger. 即使我在调试器中填充代码,这也会显示一个空列表。

ASPX Page ASPX页面

<asp:ListBox ID="myListBox" runat="server" />

I think you're looking for something like this:- 我认为您正在寻找这样的东西:

Get reader object after executing your sp 执行您的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();

Text and Value Fields can be same as well if you want it that way 如果需要,文本字段和值字段也可以相同

That's it. 而已。 It's the same way you bind items to a dropdown list. 与将项目绑定到下拉列表的方法相同。 Just used this in our recent project 刚在我们最近的项目中使用过

Hope it's helpful 希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM