Michael
Michael

Reputation: 13636

How to fill listBox Control?

I get data from DB:

        SqlCommand cmd = new SqlCommand("SELECT * FROM ItemShape", conn);

        conn.Open();

        SqlDataReader reader = cmd.ExecuteReader();

And I need to fill my control with recived data,like this :

         foreach (DataRow item in dt.Rows)
        {
           lbxObjects.DisplayMember = item["Shape"].ToString();
           lbxObjects.ValueMember = item["ID"].ToString();
        } 

But my control is empty after Debugging any idea what is wrong with the above?

Upvotes: 1

Views: 15662

Answers (3)

Ranjit Singh
Ranjit Singh

Reputation: 3735

You have to use reader as datasource of listbox

using( SqlCommand cmd = new SqlCommand("SELECT * FROM ItemShape", conn))
    {
          conn.Open();
          using(SqlDataReader reader = cmd.ExecuteReader())
          {
              if(reader.Read())
              {
                   lbxObjects.Text= item["Shape"].ToString();
                   lbxObjects.Value= item["ID"].ToString();
                   lbxObjects.DataSource=reader;
                   lbxObjects.DataBind();
              }
           }
    }

Upvotes: 1

marc_s
marc_s

Reputation: 755381

(sorry - I was too much into ASP.NET where my first approach would have worked - but in Winforms, it doesn't..)

You can use something like this - load the data into a DataTable (so your control has all the data available) and bind that:

using (SqlCommand cmd = new SqlCommand("SELECT * FROM ItemShape", conn))
{
    SqlDataAdapter dap = new SqlDataAdapter(cmd);
    DataTable tblShapes = new DataTable();
    dap.Fill(tblShapes);

    // define Display and Value members
    lbxObjects.DisplayMember = "Shape";
    lbxObjects.ValueMember = "ID";

    // set the DataSource to the DataTable 
    lbxObjects.DataSource = tblShapes;
}

That way, you don't have to manually iterate the list - the Listbox class will do that for you! You just need to define which collection of items to bind (by setting the DataSource), and which property of each item to use as DisplayMember and as ValueMember

And while you're at it - if you only need ID and Shape from that table - say so in your SELECT!

using (SqlCommand cmd = new SqlCommand("SELECT ID, Shape FROM ItemShape", conn))
{

There's no point in retrieving all columns if you really only need two of them ...

Upvotes: 3

platon
platon

Reputation: 5340

use the following code:

while (dataReader.Read())
          {
            object ID = dataReader["ID"];
            object shape = dataReader["shape"];
            lbxObjects.Items.Add(ID.ToString() + ": " +  shape.ToString());
          }

Upvotes: 1

Related Questions