Recalculating Column Values in DataGrid
By Bipin Joshi
Published: 4/24/2002
Reader Level: Intermediate
Rated: This article has not yet been rated.
Be the first to rate it!
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

The Question

I have bound a grid which contains three template cols (A, B ,C). Each Column contains a TextBox. When I bind the data I get the value of these grid TextBoxes from SQL Server. Now all that I am trying to do is when I change the value of either column A or B (TextBoxes) I want to recalculate column C. Can you please help me?

The Answer

In some cases you need to dynamically calculate the value of a DataGrid column based on values in other columns. This article will explain how to make this happen.

To begin with, we will design a web form as shown below:

When the form is displayed for the first time we will display the addition of Col1 and Col2 in Col4. In addition to this we will allow the user to change the values and get an updated total. Note that we have put TextBoxes in the ItemTemplate of the DataGrid itself.

Database Tables

In order to work with the example you will need a table in a SQL Server database with following structure.

Table Name Column Name Data Type
AdditionMaster Val1 Int
  Val2 Int

The following code is the HTML markup for the above Web form:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="RecauculateInDataGrid.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
      <asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 43px; POSITION: absolute; TOP: 29px" runat="server" Width="574px" Height="95px" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" AutoGenerateColumns="False">
        <SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
        <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
        <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
        <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
        <Columns>
          <asp:TemplateColumn HeaderText="Col 1">
            <ItemTemplate>
              <asp:TextBox id="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"val1")%>'>
              </asp:TextBox>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Col 2">
            <ItemTemplate>
              <asp:TextBox id="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"val2")%>'>
              </asp:TextBox>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Col 3">
            <ItemTemplate>
              <asp:Button id="Button1" runat="server" Text="Recalculate" CommandName="recal"></asp:Button>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="Col 4">
            <ItemTemplate>
              <asp:Label id="Label1" runat="server"></asp:Label>
            </ItemTemplate>
          </asp:TemplateColumn>
        </Columns>
        <PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC"></PagerStyle>
      </asp:DataGrid>
    </form>
  </body>
</HTML>

Note that we have set the CommandName property of the Button to recal. We will use this property later in our code while recalculating the values.

We will first write a small procedure that binds the DataGrid with our data. The following code shows that function:

public void BindGrid()
{
  string connstr=@"Integrated Security=SSPI;Initial Catalog=KnowledgeBank;Data Source=MyServer\NetSDK";
SqlConnection cnn=new SqlConnection(connstr);
SqlDataAdapter da=new SqlDataAdapter("select * from additionmaster",cnn);
DataSet ds=new DataSet();
da.Fill(ds,"additionmaster");
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}

Here we connect with the SQL Server database and populate a DataSet. We then bind the DataGrid with this DataSet.

First, we bind the DataGrid in the Page_Load event handler as shown below:

private void Page_Load(object sender, System.EventArgs e)
{
  if(!Page.IsPostBack)
  {
    BindGrid();
  }
}

When the grid is shown for the first time. We need to calculate the addition of Val1 and Val2. We will do that in the ItemDataBound event of DataGrid.

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
  {
  Label l=(Label)e.Item.Cells[3].Controls[1];
  l.Text=(int.Parse(((TextBox)e.Item.Cells[0].Controls[1]).Text) + int.Parse(((TextBox)e.Item.Cells[1].Controls[1]).Text)).ToString();
  }
}

Here we check the current item's type and then set the Label control from the column Col4 to added value.

When the user changes values from the TextBoxes and clicks on the Button, we need to recalculate the total and update Col 4. We will do that in the ItemCommand event of the DataGrid.

private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  if(e.CommandName=="recal")
  {
    if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
    {
    Label l=(Label)e.Item.Cells[3].Controls[1];
l.Text=(int.Parse(((TextBox)e.Item.Cells[0].Controls[1]).Text) + int.Parse(((TextBox)e.Item.Cells[1].Controls[1]).Text)).ToString();
    }
  }
}

Note how we have used the CommandName property to find that a Button was clicked. Inside the if…else condition we basically do the same thing as we did in the ItemDataBound event.

The following screen shows a sample run of the application. That is all there is to it.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help