Sunday, July 12, 2009

Calculations in Gridview






  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  2. DataKeyNames="ItemID" DataSourceID="sqlDataSource1"
  3. onrowdatabound="GridView1_RowDataBound">
  4. <Columns>
  5. <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
  6. <asp:BoundField DataField="ItemID" HeaderText="ItemID" InsertVisible="False"
  7. ReadOnly="True" SortExpression="ItemID" />
  8. <asp:TemplateField HeaderText="quantity" SortExpression="quantity">
  9. <EditItemTemplate>
  10. <asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
  11. </EditItemTemplate>
  12. <ItemTemplate>
  13. <asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. <asp:TemplateField HeaderText="price" SortExpression="price">
  17. <EditItemTemplate>
  18. <asp:TextBox ID="txtPrice" runat="server" Text='<%# Bind("price") %>'></asp:TextBox>
  19. </EditItemTemplate>
  20. <ItemTemplate>
  21. <asp:Label ID="Label2" runat="server" Text='<%# Bind("price") %>'></asp:Label>
  22. </ItemTemplate>
  23. </asp:TemplateField>
  24. <asp:TemplateField HeaderText="amount" SortExpression="amount">
  25. <EditItemTemplate>
  26. <asp:TextBox ID="txtAmount" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
  27. </EditItemTemplate>
  28. <ItemTemplate>
  29. <asp:Label ID="Label3" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
  30. </ItemTemplate>
  31. </asp:TemplateField>
  32. </Columns>
  33. </asp:GridView>


and the RowDataBound event is


  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  2. {
  3. if (e.Row.RowType == DataControlRowType.DataRow)
  4. {
  5. TextBox txtQuantity = (TextBox)e.Row.FindControl("txtQuantity");
  6. TextBox txtPrice = (TextBox)e.Row.FindControl("txtPrice");
  7. TextBox txtAmount = (TextBox)e.Row.FindControl("txtAmount");
  8. if (txtQuantity != null)
  9. {
  10. txtQuantity.Attributes.Add("onkeyup", "CalcAmount('" + txtQuantity.ClientID + "','" + txtPrice.ClientID + "','" + txtAmount.ClientID + "')");
  11. txtPrice.Attributes.Add("onkeyup", "CalcAmount('" + txtQuantity.ClientID + "','" + txtPrice.ClientID + "','" + txtAmount.ClientID + "')");
  12. }
  13. }
  14. }


and the javascript method will look like this


  1. <script type="text/javascript">
  2. function CalcAmount(quantity, price, amount) {
  3. document.getElementById(amount).value = parseFloat(document.getElementById(quantity).value) * parseFloat(document.getElementById(price).value);
  4. }
  5. </script>

This way when the values are changed in the quantity and price textboxes,

the corresponding amount textbox updates automatically.

No comments:

Post a Comment