Thursday, 19 January 2012

Displaying tabular data in Visual C# using ListView

ListView is extremely useful in displaying tabular data in C#. Yet, it is an easy to use control.

  1. Drag the control onto your form and note its name. In this instance, I am going to use ListView1 as name.
  2. You will have to add columns to it now. This is how you do it.
    ListView1.Columns.Add("ColumnName");
    If you have 5 columns, then you will have to do it five times.
  3. Now, you will have to have each row that you want to insert as a single dimension string array. Number of items in this array should be equal to number of added columns. If it's not, then rest of string elements will not show up. 
  4. Add the string array to a ListViewItem. For that, you will have to create a ListViewItem first. ListViewItem's constructor would allow you to pass the string array to it. Do it by typing:
    ListViewItem li = new ListViewItem(stringarray);
  5. Now add the ListViewItem to the ListView by typing:
    ListView1.Items.Add(li);
  6. Thats it! Run your application and you'll have your table beautifully displayed in tabular format. 

No comments:

Post a Comment