I'm currently using a technique I found while poking around the interwebs for flipping a datagrid's orientation in C# for a SharePoint web part. It's working correctly, pulling data from a SQL Server 2005 database and displaying it in the datagrid. I'd like to know if there is a simple way to change the column names, either using an extended property in the db, or, alternately, if I can manually set them (although I have lots of columns, so I'd prefer to add an extended property to the db and display those in place of the field names).
// Create a new data adapter and fill a dataset with the above SQL data.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Bobst Specs");
// Flip the dataset to vertical orientation.
DataSet flipped_ds = FlipDataSet(ds);
DataView dv = flipped_ds.Tables[0].DefaultView;
// Bind the dataset to a datagrid and display.
DataGrid outputGrid = new DataGrid();
outputGrid.DataSource = dv;
outputGrid.DataBind();
outputGrid.ShowHeader = false; // Remove the integer headings.
outputGrid.AutoGenerateColumns = false;
Controls.Add(outputGrid);
Here is the FlipDataSet method:
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow r = null;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
table.Rows.Add(r);
}
ds.Tables.Add(table);
}
return ds;
}
I'm also wondering if this is the "right" way to handle flipping the datagrid's orientation, or at the very least if there is a better way to do it in general.