将网格视图的两列相乘,并将其显示在新列中

Multiplying Two Columns of a gridview and show it in a new column

本文关键字:新列中 显示 两列 视图 网格      更新时间:2023-09-26

我想对网格视图的两列进行多列,并在第三列中显示它。我面临的问题在行数据绑定代码中显示了空引用异常的错误。如何解决?这在我的.cs代码中

       using System;
       using System.Collections;
       using System.Configuration;
       using System.Data;
       using System.Data.SqlClient;
       using System.Linq;
       using System.Web;
       using System.Web.Security;
       using System.Web.UI;
       using System.Web.UI.HtmlControls;
       using System.Web.UI.WebControls;
       using System.Web.UI.WebControls.WebParts;
       using System.Xml.Linq;
       using System.Globalization;
       public partial class ProjectBilling : System.Web.UI.Page
      {
         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        //AppSettingsReader configReader = new AppSettingsReader();
    }
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox txtHour = (TextBox)e.Row.FindControl("Hour");
        TextBox txtrate = (TextBox)e.Row.FindControl("RatePerHour");
        TextBox TextBoxInsertTotal = (TextBox)e.Row.FindControl("Total");
        txtHour.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txtHour.Text) + "','" + Convert.ToDouble(txtrate.Text) + "','" + Convert.ToInt32(TextBoxInsertTotal.ClientID) + "')";
        txtrate.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txtHour.Text) + "','" + Convert.ToDouble(txtrate.Text) + "','" + Convert.ToInt32(TextBoxInsertTotal.ClientID) + "')";
    }
} 
private DataSet GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;
            }
        }
    }
}
protected double CalculateTotal(double RatePerHour, int Hour)
{
    return RatePerHour * Hour;
}
protected void Add_Click(object sender, EventArgs e)
{
    try
    {
        SqlDataSource1.InsertParameters["Hour"].DefaultValue =
            ((TextBox)GridView1.FooterRow.FindControl("txtHour")).Text;
        SqlDataSource1.InsertParameters["ProjectType"].DefaultValue =
                        ((DropDownList)GridView1.FooterRow.FindControl("ddlName")).SelectedValue;
        SqlDataSource1.InsertParameters["ProjectName"].DefaultValue =
                        ((TextBox)GridView1.FooterRow.FindControl("projectnameTextBox")).Text;
        SqlDataSource1.InsertParameters["Month"].DefaultValue =
                       ((DropDownList)GridView1.FooterRow.FindControl("ddlmonth")).SelectedValue;
        SqlDataSource1.InsertParameters["Year"].DefaultValue =
           ((DropDownList)GridView1.FooterRow.FindControl("ddlyear")).SelectedValue;
        SqlDataSource1.InsertParameters["RatePerHour"].DefaultValue =
           ((TextBox)GridView1.FooterRow.FindControl("txtrate")).Text;

        SqlDataSource1.Insert();
    }
    catch (Exception ex)
    {
    }

}
protected void Button1_Click(object sender, EventArgs e)
{
}

}

我的aspx代码是:(编辑小时或每小时费率后必须更改总计算)

               <%@ Page Language="C#" AutoEventWireup="true"    CodeFile="ProjectBilling.aspx.cs" Inherits="ProjectBilling" %>
              <!DOCTYPE html>
              <html xmlns="http://www.w3.org/1999/xhtml">
              <head runat="server">
             <title>Project Billing</title>
            <link href="StyleSheet1.css" rel="stylesheet" />
            </head>
       <script>
          function multiplication(hour, rate, TextBoxInsertTotal) {
    //Your logic for multiplication
    var hour = document.getElementById(txtHour).value;
    var rate = document.getElementById(txtrate).value;
    document.getElementById(TextBoxInsertTotal).value = hour * rate;
     }
     </script>
     <body>
          <form id="form1" runat="server">
            <div>
                  <div id="menu">
                      <ul>
                <li><a href="HomePage.aspx">Home</a></li>
                <li><a href="ProjectEntry.aspx">Projects</a></li>
                <li><a href="ProjectBilling.aspx">Project Billing</a></li>
                <li><a href="report1.aspx">Report</a></li>
                <li><a href="login.aspx">Logout</a></li>
            </ul>
        </div>
        <br />
        <br />
        <h2>Project Billing</h2>
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" align="center" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ProjectBillingId" ForeColor="#333333" GridLines="None" ShowFooter="True" DataSourceID="SqlDataSource1" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="" InsertVisible="False" SortExpression="Id">
                    <FooterTemplate>
                        <asp:Button ID="Add" runat="server" Text="Insert" OnClick="Add_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Project Type" SortExpression="Project Type">
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlNames" runat="server" DataTextField="ProjectType" DataValueField="ProjectType" DataSourceID="SqlDataSource2" SelectedValue='<%# Bind("ProjectType") %>'>
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("ProjectType") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlName" runat="server" DataTextField="ProjectType" DataValueField="ProjectType" DataSourceID="SqlDataSource2">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Project Name" SortExpression="Project Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="projectNameTextBox" runat="server" Text='<%# Bind("ProjectName") %>'>
                        </asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("ProjectName") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="projectnameTextBox" runat="server">
                        </asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Hour" SortExpression="Hour">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Hour") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("Hour") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtHour" runat="server" CssClass="txthr"></asp:TextBox>
                        <%--<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ErrorMessage="FirstName is reqired" ControlToValidate="txtFirstName" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>--%>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Rate/Hour" SortExpression="Rate/Hour">
                    <EditItemTemplate>
                        <asp:TextBox ID="ratePerHourTextBox" runat="server" Text='<%# Bind("RatePerHour") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="hourLabel" runat="server" Text='<%# Bind("RatePerHour") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtrate" runat="server" ></asp:TextBox>
                        <%--<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ErrorMessage="FirstName is reqired" ControlToValidate="txtFirstName" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>--%>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total" SortExpression="Total">
                    <%--<ItemTemplate>
                        <asp:Label ID="totalLabel" runat="server" CssClass="total" Text='<%#DataBinder.Eval(Container.DataItem,("RatePerHour"))%>*<%#DataBinder.Eval(Container.DataItem,("Hour"))%>'></asp:Label>
                    </ItemTemplate>--%>
                    <%--<EditItemTemplate>
                        <asp:TextBox ID="TextBoxEditTotal" runat="server" Text='<%#CalculateTotal((double)Eval("RatePerHour"), (int)Eval("Hour")) %>'></asp:TextBox>
                    </EditItemTemplate>--%>
                     <FooterTemplate>
                        <asp:TextBox ID="TextBoxInsertTotal" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Year" SortExpression="Year">
                    <EditItemTemplate>
                        <asp:DropDownList ID="DropDownList3" runat="server" SelectedValue='<%# Bind("Year") %>'>
                            <asp:ListItem Value="-1">Year:</asp:ListItem>
                            <asp:ListItem Value="2017">2017</asp:ListItem>
                            <asp:ListItem Value="2016">2016</asp:ListItem>
                            <asp:ListItem Value="2015">2015</asp:ListItem>
                            <asp:ListItem Value="2014">2014</asp:ListItem>
                            <asp:ListItem Value="2013">2013</asp:ListItem>
                            <asp:ListItem Value="2012">2012</asp:ListItem>
                            <asp:ListItem Value="2011">2011</asp:ListItem>
                            <asp:ListItem Value="2010">2010</asp:ListItem>
                            <asp:ListItem Value="2009">2009</asp:ListItem>
                        </asp:DropDownList>
                        <%--<asp:RequiredFieldValidator ID="rfvEditYear" runat="server" ErrorMessage="Year is reqired" ControlToValidate="DropDownList3" Text="*" ForeColor="Red" InitialValue="Year:"></asp:RequiredFieldValidator>--%>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label9" runat="server" Text='<%# Bind("Year") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlyear" runat="server">
                            <asp:ListItem Value="-1">Year:</asp:ListItem>
                            <asp:ListItem Value="2017">2017</asp:ListItem>
                            <asp:ListItem Value="2016">2016</asp:ListItem>
                            <asp:ListItem Value="2015">2015</asp:ListItem>
                            <asp:ListItem Value="2014">2014</asp:ListItem>
                            <asp:ListItem Value="2013">2013</asp:ListItem>
                            <asp:ListItem Value="2012">2012</asp:ListItem>
                            <asp:ListItem Value="2011">2011</asp:ListItem>
                            <asp:ListItem Value="2010">2010</asp:ListItem>
                            <asp:ListItem Value="2009">2009</asp:ListItem>
                        </asp:DropDownList>
                        <%--<asp:RequiredFieldValidator ID="rfvYear" runat="server" ErrorMessage="Year is reqired" ControlToValidate="ddlyear" Text="*" ForeColor="Red" InitialValue="Day:"></asp:RequiredFieldValidator>--%>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Month" SortExpression="Month">
                    <EditItemTemplate>
                        <asp:DropDownList ID="DropDownList2" runat="server" SelectedValue='<%# Bind("Month") %>'>
                            <asp:ListItem Value="-1">Month:</asp:ListItem>
                            <asp:ListItem Value="January">January</asp:ListItem>
                            <asp:ListItem Value="February">February</asp:ListItem>
                            <asp:ListItem Value="March">March</asp:ListItem>
                            <asp:ListItem Value="April">April</asp:ListItem>
                            <asp:ListItem Value="May">May</asp:ListItem>
                            <asp:ListItem Value="June">June</asp:ListItem>
                            <asp:ListItem Value="July">July</asp:ListItem>
                            <asp:ListItem Value="August">August</asp:ListItem>
                            <asp:ListItem Value="September">September</asp:ListItem>
                            <asp:ListItem Value="October">October</asp:ListItem>
                            <asp:ListItem Value="November">November</asp:ListItem>
                            <asp:ListItem Value="December">December</asp:ListItem>
                        </asp:DropDownList>
                        <%--<asp:RequiredFieldValidator ID="rfvEditMonth" runat="server" ErrorMessage="Month is reqired" ControlToValidate="DropDownList2" Text="*" ForeColor="Red" InitialValue="Month:"></asp:RequiredFieldValidator>--%>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label8" runat="server" Text='<%# Bind("Month") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlmonth" runat="server">
                            <asp:ListItem Value="-1">Month:</asp:ListItem>
                            <asp:ListItem Value="January">January</asp:ListItem>
                            <asp:ListItem Value="February">February</asp:ListItem>
                            <asp:ListItem Value="March">March</asp:ListItem>
                            <asp:ListItem Value="April">April</asp:ListItem>
                            <asp:ListItem Value="May">May</asp:ListItem>
                            <asp:ListItem Value="June">June</asp:ListItem>
                            <asp:ListItem Value="July">July</asp:ListItem>
                            <asp:ListItem Value="August">August</asp:ListItem>
                            <asp:ListItem Value="September">September</asp:ListItem>
                            <asp:ListItem Value="October">October</asp:ListItem>
                            <asp:ListItem Value="November">November</asp:ListItem>
                            <asp:ListItem Value="December">December</asp:ListItem>
                        </asp:DropDownList>
                        <%--<asp:RequiredFieldValidator ID="rfvMonth" runat="server" ErrorMessage="Month is reqired" ControlToValidate="ddlmonth" Text="*" ForeColor="Red" InitialValue="Month:"></asp:RequiredFieldValidator>--%>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ConnectionStrings:ProjectManagementConnectionString%>" SelectCommand="SELECT * from Project"></asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectManagementConnectionString %>" DeleteCommand="DELETE FROM [ProjectBilling] WHERE [ProjectBillingId] = @ProjectBillingId" InsertCommand="INSERT INTO [ProjectBilling] ([Hour],[RatePerHour], [ProjectType],[ProjectName], [Month], [Year]) VALUES (@Hour,@RatePerHour, @ProjectType,@ProjectName, @Month, @Year)" SelectCommand="SELECT * FROM [ProjectBilling]" UpdateCommand="UPDATE [ProjectBilling] SET [Hour] = @Hour,[RatePerHour]=@RatePerHour, [ProjectType] = @ProjectType,[ProjectName] = @ProjectName, [Month] = @Month, [Year] = @Year WHERE [ProjectBillingId] = @ProjectBillingId">
            <DeleteParameters>
                <asp:Parameter Name="ProjectBillingId" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="Hour" Type="String" />
                <asp:Parameter Name="RatePerHour" Type="Double" />
                <asp:Parameter Name="ProjectType" Type="String" />
                <asp:Parameter Name="ProjectName" Type="String" />
                <asp:Parameter Name="Month" Type="String" />
                <asp:Parameter Name="Year" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="Hour" Type="String" />
                <asp:Parameter Name="RatePerHour" Type="Double" />
                <asp:Parameter Name="ProjectType" Type="String" />
                <asp:Parameter Name="ProjectName" Type="String" />
                <asp:Parameter Name="Month" Type="String" />
                <asp:Parameter Name="Year" Type="String" />
                <asp:Parameter Name="ProjectBillingId" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
        <br />
    </div>
</form>

我已经在我的代码中尝试了几个JavaScript选项。没有一个有效..示例代码将不胜感激。

此处的问题与 aspx 页中的控件 ID 有关。例如,在 asp 网格视图行中有以下文本框:

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Hour") %>'></asp:TextBox>

此处的文本框 ID 是"TextBox1",但在您后面的代码中搜索 ID 为"小时"的文本框

TextBox txtHour = (TextBox)e.Row.FindControl("Hour");

我认为您将文本框 ID 误认为是 asp:模板字段标头属性

<asp:TemplateField HeaderText="Hour" SortExpression="Hour">

确保在代码隐藏中搜索时使用的 ID(使用 FindControl)与 aspx 页中的控件 ID 相同(此处为文本框控件 ID)

由于代码隐藏中的 FindControl 方法(在 RowDataBound 事件中)无法找到 ID 为"小时"的文本框控件,因此会引发错误"空引用异常"

网格行中的其他控件也是如此。

已引用的答案

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                TextBox txtHour = (TextBox)e.Row.FindControl("txtHour");
                TextBox txtrate = (TextBox)e.Row.FindControl("ratePerHourTextBox");
                TextBox TextBoxInsertTotal = (TextBox)e.Row.FindControl("TextBoxInsertTotal");
                txtHour.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txtHour.Text) + "','" + Convert.ToDouble(txtrate.Text) + "','" + Convert.ToInt32(TextBoxInsertTotal.ClientID) + "')";
                txtrate.Attributes["onKeyup"] = "javascript: return multiplication('" + Convert.ToInt32(txtHour.Text) + "','" + Convert.ToDouble(txtrate.Text) + "','" + Convert.ToInt32(TextBoxInsertTotal.ClientID) + "')";

            }
        }

当您尝试查找一个(或多个控件)时,您应该使用 ID

TextBox txtHour = (TextBox)e.Row.FindControl("Hour");

您正在尝试查找 ID 为"小时"的控件。这是不存在的。它位于名为"文本框1"的代码中

This line:
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Hour")%>'>
Should be changed to this:
<asp:TextBox ID="Hour" runat="server" Text='<%# Bind("Hour")%>'>

尝试使用正确的 ID 找到它 - 在本例中为"TextBox1"

在我看来,您的网格中不存在这些控件:

TextBox txtHour = (TextBox)e.Row.FindControl("Hour");
TextBox txtrate = (TextBox)e.Row.FindControl("RatePerHour");
TextBox TextBoxInsertTotal = (TextBox)e.Row.FindControl("Total");