在Gridview itemtemplate中执行计算

时间:2011-11-01 15:47:12

标签: c# asp.net

我想在GridView

中执行计算
NetAmount = (ServiceAmount * Quantity) * Discount

我在RowDataBound编写了代码,但它无效。有人可以帮我解决这个问题吗?如果有人分享他们的知识,我将不胜感激。

我的Aspx代码:

<asp:GridView ID="GridView1" runat="server" Height="156px" Width="618px"
    AutoGenerateColumns="False" BorderWidth="1px" 
    HorizontalAlign="Justify" onrowdatabound="GridView1_RowDataBound" 
    BackColor="LightGoldenrodYellow" BorderColor="Tan" CellPadding="2" 
    ForeColor="Black" GridLines="None" onrowcommand="GridView1_RowCommand"> 

    <FooterStyle BackColor="Tan" />
    <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        <HeaderStyle BackColor="#FFFFC4" Font-Bold="True" ForeColor="#BF6000"/>
        <Columns>
            <!-- snip -->
            <asp:TemplateField HeaderText="Net Amt">
                <ItemTemplate>
                    <asp:TextBox ID="TxtNetAmt" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" runat="server" Width="55px"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    <AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:GridView>


<script type="text/javascript">
    function CalcSercode(ServiceAmount,Quantity, Discount,NetAmount)
    {
        var Quantity=parseFloat(document.getElementById(Quantity).value);
        var Discount= parseFloat(document.getElementById(Discount).value);
        var ServiceAmount=document.getElementById(ServiceAmount);
        var SerAmountValue = parseFloat((ServiceAmount * Quantity)-((ServiceAmount  *Quantity)*Discount/100));
        //var SellPriceValueRound = Math.round(SellPriceValue,4);
        var SerAmountValueRound = SerAmountValue;
        ServiceAmount.innerHTML= SerAmountValueRound ;
    }
</script>

我的cs代码:

//TextBox TxtServiceCode =  GridView1.Controls[0].Controls[0].FindControl("TxtServiceCode") as TextBox;
//DataSet dss = new DataSet();
//SqlConnection MyConnection = new SqlConnection("server=prog; database=mydatabase;UID=sa;PWD=naco123;");
//SqlCommand sqlcmd = new SqlCommand("select * from [ServiceCode]",  MyConnection);
//SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
//DataSet ds = new DataSet();
//adp.Fill(ds);
//GridView1.DataSource = ds.Tables[0];
//GridView1.DataBind();

2 个答案:

答案 0 :(得分:1)

您应该能够使用内联数据绑定语法进行计算:

<ItemTemplate>
    <%# ((Convert.ToDecimal(Eval("ServiceAmount")) * Convert.ToInt32(Eval("Quantity"))) * Convert.ToDecimal(Eval("Discount"))).ToString("C") %>
</ItemTemplate>

答案 1 :(得分:0)

一般情况下,我建议您不要在前端进行此计算,但要么在业务层中,要么在您的情况下,您似乎没有,直接进入数据库。

因此,不要将NetAmount =(ServiceAmount * Quantity)* Discount添加到您的select语句中。如果您这样做,您可以简单地将该列数据绑定到您的网格,因为它无论如何都是只读