Bappy
Bappy

Reputation: 109

Why does my listbox populated by datatable show "System.Data.DataRow" instead of the actual values?

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.

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

Upvotes: 5

Views: 26103

Answers (4)

soheil fathalian
soheil fathalian

Reputation: 1

use this

listBox1.Items.Add(dt.Rows[i][0]+"|"+dt.Rows[i][1] +"vs" + dt.Rows[i][3]);

Upvotes: 0

andy
andy

Reputation: 6079

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

ListBox1.DataSource 
  1. Link1
  2. Link2
  3. Link3

Upvotes: 3

panoptical
panoptical

Reputation: 812

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

Upvotes: 2

Shell
Shell

Reputation: 6849

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

Upvotes: 0

Related Questions