user1353517
user1353517

Reputation: 300

Display multiple columns from Database in ListView

I'm not sure why this isn't working. I'm trying to display 2 columns from my database side by side in a listview box on my form. When I use this it doesn't display any of the data correctly.

    ("SELECT Person FROM tblPeople" + " SELECT Occur FROM tblpeople" , conn);  

try
{
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
       listView1.Items.Add(reader["People"].ToString());
       listView1.Items.Add(reader["Occur"].ToString()); 
    }

So i'm looking for my data to display like this:

    John   3
    James  4
    Frank  1

As the names are coming from column People and the numbers are coming from column Occur.

Upvotes: 1

Views: 12033

Answers (2)

digEmAll
digEmAll

Reputation: 57210

To get the desired effect, you should set the view style to Details and add the second column value as sub-item.

Basically, you should do something like this:

  listView1.View = View.Details;

  listView1.Columns.Add("People");
  listView1.Columns.Add("Occur");

  while (reader.Read())
  {
      var item = new ListViewItem();
      item.Text = reader["People"].ToString();        // 1st column text
      item.SubItems.Add(reader["Occur"].ToString());  // 2nd column text
      listView1.Items.Add(item);
  }

Upvotes: 4

walther
walther

Reputation: 13600

Method Add() adds every time a new item to the collection. If your item consists of values from two objects, probably the easiest way would be to create a new item to encapsulate it, so you can easily bind it to your controls.

Consider something like this:

public class MyNewObject
{
    public string People { get;set; }
    public string Occur { get;set; }

    public MyNewObject(string p, string o)
    { 
        People = p;
        Occur = o;
    }
}

and then just

while (reader.Read())
{
    listView1.Items.Add(new MyNewObject(reader["People"].ToString(),reader["Occur"].ToString()));
}

Upvotes: 0

Related Questions