1

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.

4
  • 1
    Why don't you just put SELECT person, occur FROM tblpeople? Commented Apr 30, 2012 at 21:54
  • Good tip! I'll change it to that but that doesn't really answer what I asked. Commented Apr 30, 2012 at 21:55
  • Have a look at this question. Commented Apr 30, 2012 at 21:57
  • Please don't prefix your titles with "C#" and such. That's what tags are for. Commented Apr 30, 2012 at 22:05

2 Answers 2

4

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);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

@user1353517: Good. However, if you want to display tables you might also have a look at DataGridView's ;)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.