简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM