Reputation: 5
I want to display the values from column named "total" on a label in my GridView footer.
The value of "total" column is same along every row so it does not matter which ever cell is chosen as long as we are in that column.
I am using a template-field for my column "total" and I am hiding it by making its visibility=false. so what i want is i want to display the value from my column named total on to a label which is inside my gridview
Here is the code sample I have tried, but its giving an error:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int total;
if (e.Row.RowType == DataControlRowType.DataRow)
{
total = Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString());
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblamount7 = (Label)e.Row.FindControl("Label27");
lblamount7.Text =total.ToString(); // use of unassigned local variable 'total'
}
}
this is the aspx of the hidden column '> '>
Upvotes: 0
Views: 3126
Reputation: 62841
It think you need parentheses around your DataRowView cast -- DataItem["total"] does not exist:
Change this:
total = Convert.ToInt32((DataRowView)e.Row.DataItem["total"].ToString());
to
total = Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString());
--EDITS
You need to define total outside of the RowDataBound procedure and initialize it to 0. Also, please note the use of "+=" -- I assume you want a running total from each of your columns. If not, change that back to just "=" which will grab the last total in your data rows.
private int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
total += Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString());
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblamount7 = (Label)e.Row.FindControl("Label27");
lblamount7.Text =total.ToString();
}
}
Good luck.
Upvotes: 0
Reputation: 716
For hiding the column take a Hiddeneeild in the Template-Field of GridView. The syntax will be like
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Total") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now to calculate total and show it in footer of GridView you can do like
int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Total"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount7 = (Label)e.Row.FindControl("lblTotal");
lblamount7.Text = total.ToString();
}
}
It will surely work. Good Luck and do comment if it worked.
Upvotes: 1