5

I am trying to populate a listview or a listbox from database using C#. I am using datatable to grab data. I am using this code below. But listview or the listbox is populating something like "System.Data.DataRow" text. Where I have something else in my database. Pls Help

query = "select itemtag from tbl_inventory order by itemtag";
DataTable dt = con.DataTable(query);
int count = dt.Rows.Count;
if (count >0)
{
    //listView1.Items.Clear();
    listBox1.Items.Clear();

    for (int i = 0; i < count; i++)
    {
        //listView1.Items.Add(dt);
        listBox1.Items.Add(dt.Rows[i].ToString());
    }
}

As you see I am getting output like "System.Data.DataRow",where I have something else in my database

Any help?

Steve
  • 208,592
  • 21
  • 221
  • 278
Bappy
  • 109
  • 1
  • 3
  • 13

4 Answers4

3

If your using a listbox then directly use the DATASOURCE property...

ListBox1.DataSource 
  1. Link1
  2. Link2
  3. Link3
Community
  • 1
  • 1
andy
  • 5,802
  • 2
  • 25
  • 49
2

Unless your DataTable is 1-dimensional (in which case, why are you using a DataTable), then your code should be:

listBox1.Items.Add(dt.Rows[i][columnIndexHere].ToString());
panoptical
  • 753
  • 1
  • 7
  • 22
0
 listBox1.Items.Add(dt.Rows[i][0].ToString());

But, this will inserts only first column data into listview. if you want to add subitem also then use it.

 ListItem li = listBox1.Items.Add(dt.Rows[i][0].ToString());
 li.SubItems.Add(dt.Rows[i][1].ToString());
 li.SubItems.Add(dt.Rows[i][2].ToString());
Shell
  • 6,680
  • 10
  • 36
  • 70
0

use this

listBox1.Items.Add(dt.Rows[i][0]+"|"+dt.Rows[i][1] +"vs" + dt.Rows[i][3]);
Android
  • 1,410
  • 4
  • 11
  • 22