Rob Farley

Rob Rob Farley has been consulting in IT since completing a Computer Science degree with first class honours in 1997. Before moving to Adelaide, he worked in consultancies in Melbourne and London. He runs the development department in one of Australia's leading IT firms, as well as doing database application consultancy and training. He heads up the Adelaide SQL Server User Group, and holds several Microsoft certifications.

Rob has been involved with Microsoft technologies for most of his career, but has also done significant work with Oracle and Unix systems. His preferred database is SQL Server and his preferred language is C#. Recently he has been involved with Microsoft Learning in the US, creating and reviewing new content for the next generation of Microsoft exams.

Over the years, Rob's clients have included BP Oil, OneLink Transit, Accenture, Avanade, Australian Electorial Commission, the Chartered Institute of Personnel and Development, the Royal Borough of Kingston, Help The Aged, Unisys, Department of Treasury and Finance (Vic), National Mutual, the Bible Society and others.

Did you mean to come here? My blog is now at http://msmvps.com/blogs/robfarley



20 April 2005

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);