Calculating the product of two columns within a gridview and displaying the result in a separate column

I need to multiply two columns in my gridview and display the result in a third column. However, I am encountering a null reference exception error in the rowdatabound code. How can I resolve this issue? Below is my .cs code:

       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)
{

}

}

Here is my aspx code (the total calculation should change after editing the hour or RatePerHour):

               <%@ 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) {
    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>
                ... (columns omitted for brevity)
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor...

I have tried various JavaScript options within my code, but none of them seem to work. Any sample code you could provide would be greatly appreciated.

Answer №1

The issue at hand pertains to the ID of your control in the aspx page. For example, you have the following text box in an asp grid view row:

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

The ID of the text box here is 'TextBox1', however, in the code behind, you are attempting to find a text box with the ID 'Hour'

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

It seems like you might have confused the TextBox Id with the asp:TemplateField header attribute

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

Make sure that the ID you use for searching in the code behind (via FindControl) matches the control's ID in the aspx page (the ID of the text box control here)

Since the FindControl method (within the RowDataBound event) in the code behind cannot locate a TextBox control with the ID 'Hour', it is triggering a 'null reference exception' error

This applies to other controls within your Grid Row as well.

UPDATED SOLUTION

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) + "')";


            }
        }

Answer №2

Make sure to use the correct ID when searching for a control or controls.

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

If you are looking for a control with the ID "Hour" and it does not exist, check if it is actually named "TextBox1" in your code.

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")%>'>

Ensure you are using the correct ID - perhaps "TextBox1" in this scenario.

It appears that none of these controls are present in your grid:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to initiate a new session, Webdriver.io receives an HTML response from selenium

Currently, I am attempting to execute my selenium tests using webdriver.io. However, the test runner is encountering failure when attempting to establish a session: [18:12:36] COMMAND POST "/session" [18:12:36] DATA {"desiredCapab ...

Retrieve information from PHP by utilizing jQuery and transmit it back to PHP

My current setup looks like this: <div class="container"> <ul> <li data-owner="93"><a href="javascript:void(0);"></a></li> <li data-owner="94"><a href="javascript:void(0);"></a>< ...

The Print Preview Displays No Content When an External Stylesheet Reference is Included in the Printable HTML Content

Is there a way to print the contents of a DIV on a webpage? Currently, I am using JavaScript to retrieve the contents of the div and then passing it to a new window object where I call the .print() function. The text contents and images are displayed corre ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

How can a modern browser retrieve a json.gz file without relying on external libraries?

What can be done to let the browser know that a json.gz file is compressed JSON, for example: {"abc":1}, and automatically unpack it into a JavaScript object? I attempted this approach, but it was not successful: https://en.wikipedia.org/wiki/JS ...

Javascript Popup Functionality Failing to Execute

It seems that the popup link does not function properly when placed between the <script> tags. if(data.userdata["money_back"] == 1){ chat_list += '<a data-popup-open="popup-90">Download</a>'; } On the other hand, when the pop ...

Arranging a list of strings in a BsonArray

I have a BsonArray filled with string IDs that I need to sort in ascending order before saving them to the database. Using MongoDB's C# driver, here is an example of the BsonArray: "IDPart" : [ "BO0001", "CO0001", "BD0002", "BD0001"] ...

Why does req.body not capture the value of the <textarea> in a Node.js Express application?

I am currently developing a Node.js express app and encountering an issue with my HTML form (inputForm.html): <form action="/" method="post"> Name: <br> <input type="text" name="name" size="45"> <br> Document: <br> ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

Ensure that only a single onmouseover event is triggered when hovering over multiple elements

I want to create a simple code snippet like the one below: <span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span> However, I need to ensure that when hovering ove ...

Numeric expression of space

Is there a way to include spaces as decimal number separators? Currently, the format is 23456.00, but it needs to be 23 456 I've managed to eliminate the .00 using toFixed, but I'm struggling with adding the space separator. {{parseFloat(post.m ...

Ways to extract the value or string from a ql-editor using selenium

Looking to extract text from the ql-editor. The following code works fine with other text fields like email or password fields, but not in the ql-editor. The variable checkText ends up being null. public static void SendKeysElement(IWebDriver webDrive ...

Getting an out-of-range exception (System.ArgumentOutOfRangeException) in C# Razor pages while attempting an AJAX call

I have a razor page model that contains a get-method. public IActionResult OnGetDuration([FromBody]int id) { Subject subject = _service.GetSubjectById(id); int duration = subject.LessonsPerWeek; return new JsonResult('a&apo ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Clarifying the confusion surrounding AngularJS $q, promises, and assignments

Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - http://plnkr.co/edit/ZK ...

Reducing the length of Javascript code

Recently, I have been working on a project where I needed to use a piece of Javascript code to insert text into an input element when its label is double-clicked. $(document).ready(function() { $('#name-label').dblclick(function(){ $ ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

Warning: The `children` attribute returned a value of NaN

I am currently working on a tic tac toe web application. I encountered an issue when clicking the "Ver Ranking" button, as it displays a warning message that I'm unsure how to address: Warning: Received NaN for the `children` attribute. If this is exp ...