Reputation: 109
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());
}
}
, where I have something else in my database
Upvotes: 5
Views: 26103
Reputation: 1
use this
listBox1.Items.Add(dt.Rows[i][0]+"|"+dt.Rows[i][1] +"vs" + dt.Rows[i][3]);
Upvotes: 0
Reputation: 6079
If your using a listbox then directly use the DATASOURCE property...
ListBox1.DataSource
Upvotes: 3
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
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