Add column names to listview using dataSet in C#


When we need to populate various reports, usually we also need to supply customized column names too. We can easily grab column name from the database using objects like DataSet in C#

In our example, we use SQL database objects as follows.

AccountReportAdapter = new SqlDataAdapter(sql, con);
AccountReportDS = new DataSet();
AccountReportAdapter.Fill(AccountReportDS);

Get started with a foreach statement and store the names into a List collection object.

List<string> hds = new List<string>();

hds.Clear();
foreach (DataColumn c in Common.AccountReportDS.Tables[0].Columns)
{
hds.Add(c.ColumnName.ToString());
}

The hds list simply store the column name, just like an array does. Later we can use the list for supplying heads for ListView  as follows

public void ReportHeader(List<string> ar)
{
ColumnHeader headers = new ColumnHeader();
listView1.View = View.Details;
headers.Text = ” “;
headers.Width = 0;
listView1.Columns.Add(headers);
foreach (var htext in ar)
{
headers = new ColumnHeader
{
Text = htext.ToString(),
Width = htext.ToString().Length * 20
};
listView1.Columns.Add(headers);
}
}

if (hds != null) ReportHeader(hds);

 

1 thought on “Add column names to listview using dataSet in C#

  1. Pingback: How to change font of listview items at runtime in C# | DeveloperM – A developer's Manual

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.