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
  • 213,761
  • 22
  • 232
  • 286
Bappy
  • 109
  • 1
  • 3
  • 14

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,979
  • 2
  • 27
  • 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
  • 782
  • 1
  • 8
  • 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,818
  • 11
  • 39
  • 70
0

use this

listBox1.Items.Add(dt.Rows[i][0]+"|"+dt.Rows[i][1] +"vs" + dt.Rows[i][3]);
Android
  • 1,420
  • 4
  • 13
  • 23