Tuesday, January 13, 2009

Add / Insert a row to a gridview

In many cases we come across the situation where we have to add a row to a gridview. We can create a new grid view row through the GridViewRow class. But there is no property/method to a grid to add the row to the gridview. Not even the Gridview.Rows property has any methor to add/insert a row.
In a situation i had to add a footer to show the total of the fields displayed in the gridview. I knew that i could set the value in footer through RowDataBound event of GV by inspection like

if(e.Row.RowType==DataControlRowType.Footer)
{

}

here e is the GridViewRowEventArgs parameter to the event.
But i was looking for something new. I found i can create the row through GridViewRow which takes the rowindex, rowtype ... parameters.
Then i found i can cast the parent of any row of gridview to a table but cannot cast the gridview directly to table. So here is how i implemented...
::::::::::::::::::::::::::::::::::::::::::::::::::::::

gvTaxPlanning.DataSource = dv;
gvTaxPlanning.DataBind();
if (gvTaxPlanning.Rows.Count > 0)
{
GridViewRow gvr = new GridViewRow(gvTaxPlanning.Rows.Count, gvTaxPlanning.Rows.Count, DataControlRowType.Footer, DataControlRowState.Normal);
TableCell tc = new TableCell();
tc.Text = "Total";
gvr.Cells.Add(tc);
tc = new TableCell();
tc.Text = (tEQTax + tMFTax + tULTax + tBulTax + tBankTax + tAssetTax).ToString(GlobalSettings.FloatNumberFormatter);
gvr.Cells.Add(tc);
gvr.Font.Bold = true;
gvr.BackColor = System.Drawing.ColorTranslator.FromHtml("#000084");
gvr.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
Table tab = (Table)gvTaxPlanning.Rows[0].Parent;
tab.Rows.Add(gvr);
}

I thought that it will need the
gridView.ShowFooter = true; to show the new row i have added as it was footer and by default grid doesn't show the footer.
But not... it ws showing the footer whithout setting it to true...
And one more thing... The RowCreated event is not fired when you add this new row.

Read More http://blog.falafel.com/2007/04/12/DynamicallyAddRowsToAGridView.aspx

2 comments:

RNDTECHNOLOGIES said...

Good thought.

Puneflowersdelivery said...

Send flowers to Pune, flowers to Pune delivery,flowers to Pune, Pune flowers delivery, flowers Pune, Online flowers to Pune.