Как умножить два столбца GridView в один
Я хочу, чтобы иметь возможность ввести значение в текстовое поле количество, а затем:
- Умножьте это значение на единицу "квадратный фут" и сохраните результат в "Итог"
- Суммируйте каждый промежуточный итог и сохраните результат в "Всего"
Это то, что я до сих пор:
<asp:GridView runat="server" ID="gridViewBuildOfficeSpace" AllowPaging="false"
AllowSorting="false" AutoGenerateDeleteButton="false"
AutoGenerateEditButton="false" AutoGenerateSelectButton="false"
AutoGenerateColumns="false" ShowFooter="true"
onrowdatabound="gridViewBuildOfficeSpace_RowDataBound">
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Size" HeaderText="Size" />
<asp:BoundField DataField="Dimensions" HeaderText="Dimensions" />
<asp:TemplateField HeaderText="Unit Square Foot">
<ItemTemplate>
<asp:Label runat="server" ID="unitSquareFootLabel" Text='<%# Eval("UnitSquareFoot") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" >
<ItemTemplate>
<asp:TextBox AutoPostBack="true" ID="gridviewQuantityItem" runat="server"/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="Label12" Text="Total Size: " runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SubTotal">
<ItemTemplate>
<asp:Label ID="gridViewItemSubTotal" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="totalSizeDisplayLabel" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Код позади:
protected void gridViewBuildOfficeSpace_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < gridViewBuildOfficeSpace.Rows.Count; i++)
{
gridViewBuildOfficeSpace.Rows[i].Cells[5].Text = Convert.ToString(Convert.ToDouble(gridViewBuildOfficeSpace.Rows[i].Cells[3].Text)*Convert.ToDouble(gridViewBuildOfficeSpace.Rows[i].Cells[4].Text));
}
}
Я попытался использовать в TextBox OnTextChanged, а затем попытался найти соответствующие элементы управления, чтобы превратить их в целые, умножить их и отобразить значение в метке, но я либо получаю нулевые ссылки относительно unit Square FootLabel.
Но с помощью приведенного выше кода я получаю строку ввода не в правильном формате.
Как бы я это сделал?
1 ответ
У вас есть 2 варианта.
- Делайте вычисления на стороне клиента с помощью jQuery или javascript
- Делайте их на бэкэнде с помощью C# (включает обновление страницы)
Я бы порекомендовал первый вариант. Вот пример: так что gridview нужно немного изменить. Я добавил несколько имен классов CSS, на которые можно легко ссылаться с помощью JS и jQuery:
<asp:GridView runat="server" ID="gridViewBuildOfficeSpace"
AutoGenerateColumns="False" ShowFooter="True"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="DESCRIPTION" HeaderText="Description" />
<asp:BoundField DataField="SIZE" HeaderText="Size" />
<asp:BoundField DataField="DIMENSIONS" HeaderText="Dimensions" />
<asp:TemplateField HeaderText="Unit Square Foot">
<ItemTemplate>
<asp:Label runat="server" ID="unitSquareFootLabel" Text='<%# Eval("SQFOOT") %>' />
</ItemTemplate>
<ItemStyle CssClass="unitSquareFoot" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" >
<ItemTemplate>
<asp:TextBox ID="gridviewQuantityItem" runat="server" onblur="calculate()"/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="Label12" Text="Total Size: " runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SubTotal">
<ItemTemplate>
<asp:Label ID="gridViewItemSubTotal" runat="server" />
</ItemTemplate>
<ItemStyle CssClass="SubTotal" />
<FooterTemplate>
<asp:Label ID="totalSizeDisplayLabel" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Затем в нижней части страницы перед закрывающим тегом body добавьте js:
<script>
function calculate() {
//get the gridview
gv = $('#gridViewBuildOfficeSpace');
//Find the number of rows in the grid
var rowCount = gv.find('tr').length;
//Iterate through each row looking for the input boxes (This section is for the ROW totals)
for (var i = 0; i < rowCount; i++) {
//Iterate through each text box
var row = gv.find("tr:eq(" + i + ")");
//Find the input text field
row.find(":input[type=text]").each(function () {
//Get the quantity value
quantity = $(this).val();
//Get the sqfoot
sqfoot = row.find("[class$='unitSquareFoot']").text();
//Add the text to the subtotal field
row.find("[class$='SubTotal']").text(quantity * sqfoot);
});
}
}
</script>
Это предполагает, что вы добавляете ссылку на jQuery для его работы...