Reputation: 1151
I need to set total of a particular column in a gridview.
My code is:
<asp:TemplateField>
<HeaderTemplate>
Amount
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblAmt" HeaderText="Amount" runat="server"
Text='<%# Eval("Amount")%>' Visible="true">
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalAmt" runat="server" />
</FooterTemplate>
</asp:TemplateField>
and then:
decimal totProfit = 0M;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblAmt = (Label)e.Row.FindControl("lblAmt");
decimal Profitprice = Decimal.Parse(lblAmt.Text);
totProfit += Profitprice;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblTotalAmt = (Label)e.Row.FindControl("lblTotalAmt");
lblTotalAmt.Text = totProfit.ToString();
}
}
But error came like:
Input string was not in a correct format.
Upvotes: 2
Views: 4875
Reputation: 40990
This may be because your lblAmt
may contains a value that is not valid for decimal. So make sure your value should be parse to decimal. So for safer side use Decimal.TryParse
like this
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblAmt = (Label)e.Row.FindControl("lblAmt");
decimal Profitprice = 0;
if(Decimal.TryParse(lblAmt.Text, out Profitprice));
{
totProfit += Profitprice;
}
}
Upvotes: 2
Reputation: 37880
There is an error that's recognized by MS during integer conversions that may be coming into play here (http://support.microsoft.com/kb/942460)
The other option, is to ensure that it's a number in the 'Amount' field.
decimal totProfit = 0M;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblAmt = (Label)e.Row.FindControl("lblAmt");
decimal Profitprice;
if (Decimal.TryParse(lblAmt.Text, Profitprice) ) {
totProfit += Profitprice;
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblTotalAmt = (Label)e.Row.FindControl("lblTotalAmt");
lblTotalAmt.Text = totProfit.ToString();
}
}
Upvotes: 2