I decided to write this post because I always encounter this kind of issue so many times before at the forums. The main question is that they want to automatically calculate the totals when a user enter an amount from the TextBox control that is residing in the GridView template. So this example shows the basic way on how to achieve this with the server side manipulations.
Note that this demo requires that you know the basics of ADO.NET and for binding a GridView control with data from database.
Here are the code blocks below:
Assuming that we have this GridView mark up below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
ShowFooter="true">
<Columns>
<asp:BoundField DataField="ItemDescription" HeaderText="Item"/>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
ontextchanged="TextBox1_TextChanged">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note: Be sure to set ShowFooter to TRUE so that the footer will show when the GridView is rendered in the page.
The following are the code blocks for binding the GridView with data from database:
private string GetConnectionString(){
//Where MYDBConnection is the connetion string that was set up in the web config file
return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
}
// Method for Binding the GridView Control
private void BindGridView(){
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM TableName";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
protected void Page_Load(object sender, EventArgs e){
if (!Page.IsPostBack)
{
BindGridView(); //Bind GridView on initial postabcks
}
}
And here’s the code block for calculating the Totals:
//Calculate the Totals in the TextBox rows
protected void TextBox1_TextChanged(object sender, EventArgs e){
double total = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
TextBox tb = (TextBox)gvr.Cells[1].FindControl("TextBox1");
double sum;
if(double.TryParse(tb.Text.Trim(),out sum))
{
total += sum;
}
}
//Display the Totals in the Footer row
GridView1.FooterRow.Cells[1].Text = total.ToString();
}
Note:
Be sure to set AutoPostBack to TRUE for your TextBox control so that the TextChanged event will fire up.
That’s it! Hope you will find this example useful!