Populating data in multiple columns using WinForms ListView

In this article, I would like to discuss a brief on how to bind data in multiple columns using ListView in WinForms.  It is preferable to go for a ListView rather than a ListBox in Winforms to bind multiple columns. Below is the little tricky code to do so:

// Adding ListView Columns
lstView.Columns.Add("Id", 245, HorizontalAlignment.Left);
lstView.Columns.Add("Name", 241, HorizontalAlignment.Left);
lstView.Columns.Add("Mobile Number", 245, HorizontalAlignment.Left);

// Getting the data to a datasource
DataTable dt = businessComponent.GetData(Id);

string[] Str = new string[3];
ListViewItem newItm;
foreach (DataRow dataRow in dt.Rows)
{
           Str[0] = dataRow["Id"].ToString();
           Str[1] = dataRow["Name"].ToString();
           Str[2] = dataRow["Mobile"].ToString();
           newItm = new ListViewItem(Str);
           lstView.Items.Add(newItm);
}

To show the data in Details form (tabular form) we need to set ‘View’ property of the ListView to Details. By default it is set to LargeIcon  out of the 5 values - LargeIcon, Details, SmallIcon, List, Tile.
We can do many more customizations for ListView, like setting the width of the columns, colors, fonts, etc  with ListView as it is designed to display the data.

Comments

Post a Comment

Popular posts from this blog

Convert XElement to DataTable

Enable mouse scroll-wheel in VB6

Performance of 'is' vs typeof (Reflection) in C#