Few days ago I blogged about how you can create a
running total with the TextBoxes inside the GridView control. The article about
the running total can also be found on the GridViewGuy website. One of the
readers pointed out that the sample code would not work if the user will edit
the amount. This was offcourse a big problem if the users make a mistake and try
to edit it. I worked on the problem and found a simple solution. The solution to
this problem is to iterate through the textboxes and calculate the score on each
onfocus event. Take a look at the code below:
<asp:GridView ID="gvSales" runat="server" AutoGenerateColumns="False"
ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server"
Text='<%# Eval("ProductName") %>' />
</ItemTemplate>
<FooterTemplate>
<b>Total</b>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:TextBox ID="txtPrice" onChange="Add()" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtTotal" Font-Size="XX-Large" Font-Bold="true"
Enabled="false" BackColor="Khaki" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is the simple JavaScript function:
<script language="javascript">
// This function should iterate through all the TextBoxes and get the values
function Add()
{
var obj = window.event.srcElement;
var tBox;
// clear the sum variable
var sum = 0;
if(obj.tagName == "INPUT" && obj.type == "text")
{
// Iterate through all the TextBoxes
tBox = document.getElementsByTagName("INPUT");
for(i = 0; i< (tBox.length - 2) ; i++)
{
if(tBox[i].type == "text")
{
// The Number function forces the JavaScript
to recognizes the input as a number
sum += Number(tBox[i].value);
}
}
}
// set the value in the total box
document.getElementById("gvSales_ctl07_txtTotal").innerText = sum;
}
</script>
The above code will fix the problem. I will soon update the article and the
sample files. Hope it helps!
powered by IMHO 1.3