DataView column names
Today I had a SQL query which I wanted to make a table from in ASP.Net (using C#). I didn't want to use a DataGrid and bind it, I wanted to be able to loop through the fields and display it as I used to do for a RecordSet. The odd 'switch' statement to alter the formatting, that type of thing. Nice and generic, that I can pass DataViews into, so that whenever I have a field with a particular name, I can display a link, or whatever.
With an old ADO recordset, I could just refer to rs.Fields[i].Name for the column name and rs.Fields[i].Value for the values. But no such luck in .Net.
The answer turned out to be to refer to the Table property of the DataView. Then you have refer to the Columns property, and get the ColumnName out of there. Like this:
// 'dv' is my DataView. You should use better variable names than this.
Table t = new Table();
TableRow tr = new TableRow();
for (int i=0;i<dv.Table.Columns.Count;i++)
{
tc = new TableCell();
tc.HorizontalAlign = HorizontalAlign.Center;
tc.Text = dv.Table.Columns[i].ColumnName;
tr.Cells.Add(tc);
}
t.Rows.Add(tr);
foreach (DataRowView dvr in dv)
{
TableRow tr = new TableRow();
for (int i=0;i<dv.Table.Columns.Count;i++)
{
TableCell tc = new TableCell();
// switch on dv.Table.Columns[i].ColumnName if you want
tc.Text = dvr[i].ToString();
tr.Cells.Add(tc);
}
t.Rows.Add(tr);
}
return(t);