
Introduction
This article is just an example of Neeraj Jain's work in Displaying Vertical Rows in a DataGrid.
Background
Here I designed a C# application with a DataGridView
containing some information from a DataTable
object in the normal mode (Horizontal Rows). When you press on "Flip Datagride" button, the data grid displays the same table but in the Flipped mode (Vertical Rows).
Using the Code
Create a new C# .NET 2005 Windows Application.
Add the buttons and the DataGridView
object on the Form
as shown in the picture.
Declare the DataSet
and DataTable
object as follows:
public partial class Form1 : Form
{
DataSet ds = null;
DataTable dt = null;
public Form1()
{
InitializeComponent();
}
Create a new method that creates and returns a DataTable
object filled with some data:
private static DataTable GetCustomers()
{
DataTable table = new DataTable();
table.TableName = "Customers";
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Price", typeof(string));
table.Columns.Add("Country", typeof(string));
table.Rows.Add(new object[] { "Mohamad", "1700", "Egypt" });
table.Rows.Add(new object[] { "Tarek", "550", "Syria" });
table.Rows.Add(new object[] { "Gamal", "762", "Saudi Arabia" });
table.AcceptChanges();
return table;
}
Create OnLoad
event and add the following code:
private void Form1_Load(object sender, EventArgs e)
{
ds = new DataSet();
dt = new DataTable();
dt = GetCustomers();
ds.Tables.Add(dt);
DataView my_DataView = ds.Tables[0].DefaultView;
this.my_DataGrid.DataSource = my_DataView;
}
Create 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;
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;
}
Add the button click event as follows:
private void butFlip_Click(object sender, EventArgs e)
{
DataSet new_ds = FlipDataSet(ds);
DataView my_DataView = new_ds.Tables[0].DefaultView;
this.my_DataGrid.DataSource = my_DataView;
butFlip.Enabled = false;
butNormal.Enabled = true;
}
private void butNormal_Click(object sender, EventArgs e)
{
DataView my_DataView = ds.Tables[0].DefaultView;
this.my_DataGrid.DataSource = my_DataView;
butFlip.Enabled = true;
butNormal.Enabled = false;
}
private void butExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Now build and run the application.
History
- 23rd June, 2007: Initial post