LivstView Column not aligned with ListViewItem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nghivo
    New Member
    • Apr 2007
    • 17

    #1

    LivstView Column not aligned with ListViewItem

    I created the listview as followed:

    Code:
    ListView lvContent = new ListView();
    
    //Add the column header
    lvContent.Columns.Add("Col1");            
    lvContent.Columns.Add("Col2");
    lvContent.Columns.Add("Col3");
    lvContent.Columns.Add("Col4");
    lvContent.Columns.Add("Col5");
    Then I have a CSV file with 5 columns. I read the file to populate the rows:

    Code:
    char[] delim = new char[] {','};
    
    System.IO.StreamReader reader = new System.IO.StreamReader(fileName); 
    string line;
    while ((line = reader.ReadLine()) != null)
    {
      String[] arr = line.Split(delim);
      lvi = new ListViewItem();
      for (int i = 0; i < arr.Length; i++)  // arr.Length is always 5
      {
        lvi.SubItems.Add(arr[i]);
      }
      this.lvContent.Items.Add(lvi);
    }
    The problem is the column header is not aligned with the data in the listviewitem record. In fact, the columns in listviewitem records is shifted to the right by one position.

    Is there anything wrong with my code or it is the nature of CSV file?

    Thanks
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Try Trim(), there's probably an extra space in the data
    Example "123, 456" the 123 would be "123" and the 456 would be " 456"

    Comment

    • nghivo
      New Member
      • Apr 2007
      • 17

      #3
      My problem is what is the first cell in the row goes to the 2nd column, and the 2nd cell goes to the 3rd row, so on. So all the cells in a row shifted to the right by one column.

      I found the problem. It has something to do with the ListViewSubItem .
      There is a weird relationship b/w all ListViewSubItem objects (in a ListViewItem)an d the first ListViewSubItem .

      In order to align all cells properly, I changed my code as followed:

      Code:
      lvsi = new ListViewItem.ListViewSubItem();
      lvsi.Text = arr[i];
      lvi.SubItems.Insert(i, lvsi);
      and these lines replace the single line

      Code:
      lvi.SubItems.Add(arr[i]);
      So, don't use Add but use Insert.

      Comment

      Working...