简体   繁体   中英

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

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

I think you're looking for something like this:-

Get reader object after executing your 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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