Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Wednesday, October 3, 2007

Loading a GridView into a DataTable and then back to another GridView

First, Loading a GridView into a DataTable, dt:


private void initDataTable()
{

int i = 0;
int j = 0;
int totRow = GridView1.Rows.Count;
int totCol = GridView1.Rows[0].Cells.Count;
// Set the table headers
string[] arrHeaders = {"Symbol","Name","Exchange" };
// Get the table headers
for (j = 0; j < totCol; j++)
{
// The commented line would work if the Gridview had Column HeaderText
//dt.Columns.Add(new DataColumn(GridView1.Columns[col].HeaderText, typeof(string)));

// Instead I use the Headers array, arrHeaders
dt.Columns.Add(new DataColumn(arrHeaders[j].ToString(), typeof(string)));
}
DataRow dr;
for (i = 0; i < totRow; i++)
{
dr = this.dt.NewRow();
for (j = 0; j < totCol; j++)
{
dr[j] = GridView1.Rows[i].Cells[j].Text;
}
this.dt.Rows.Add(dr);
}
}

Then back to another GridView:


private void fillGridView2()
{
if (dt.Rows.Count > 0)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
dt.Rows.Add(dt.NewRow());
GridView2.DataSource = dt;
GridView2.DataBind();

int TotalColumns = GridView2.Rows[0].Cells.Count;
GridView2.Rows[0].Cells.Clear();
GridView2.Rows[0].Cells.Add(new TableCell());
GridView2.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView2.Rows[0].Cells[0].Text = "No Record Found";
}
}

The no record found code was from this link.

No comments: