C sharp LISTVIEW - help please?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: C sharp LISTVIEW - help please?

  1. #1
    Join Date
    Jan 2009
    Posts
    1

    Question 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...

  2. #2
    Join Date
    Jul 2006
    Posts
    97

    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.
    Using .NET 2.0

  3. #3
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    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.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center