C sharp LISTVIEW - help please?
here how the code looks:
connection.Open();
string txtSql = "select EmployeeID, Lastname, FirstName, Title, TitleOfCourtesy, HireDate, Address, City, Homephone from Employees";
SqlCommand cmd = new SqlCommand(txtSql, connection);
SqlDataReader dr = cmd.ExecuteReader();
ListViewItem a;
while (dr.Read())
{
a = new ListViewItem();
for (int i=1; i < dr.FieldCount; i++)
{
a.Text = Convert.ToString(dr.GetValue(i));
ListViewItem.ListViewSubItem bla = new ListViewItem.ListViewSubItem(a, a.Text.ToString());
a.SubItems.Add(bla);
}
listView1.Items.Add(a);
}
dr.Close();
connection.Colse();
The output in the listview1 is: http://img140.imageshack.us/img140/3005/notcm1.png
but the first collumn should be filled from the id collumn of the db table and not phone!
What I'm missing?! Please somebody help...
Re: C sharp LISTVIEW - help please?
I believe this should fix the problem:
Code:
while (dr.Read())
{
a = new ListViewItem();
a.Text = Convert.ToString(dr.GetValue(0));
for (int i=1; i < dr.FieldCount; i++)
{
a.SubItems.Add(dr.GetValue(i));
}
listView1.Items.Add(a);
}
ListViewItem.Text sets the text of the first column of the item. SubItems are the next columns.
And use CODE tags when you post your code.
Re: C sharp LISTVIEW - help please?
Please use code tags in future.
Your problem is that you're setting the text of the list view item every time around the loop. So you're resetting the first column's text to being the nth columns text.
To fix it do this :
Code:
ListViewItem a;
while (dr.Read())
{
a = new ListViewItem();
a.Text = Convert.ToString(dr.GetValue(0));
for (int i=1; i < dr.FieldCount; i++)
{
ListViewItem.ListViewSubItem bla = new ListViewItem.ListViewSubItem(a, a.Text.ToString());
a.SubItems.Add(bla);
}
listView1.Items.Add(a);
}
Darwen.