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);
One thought on “Add column names to listview using dataSet in C#”