Click here to Skip to main content
14,739,236 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am a newbie in C# and this is my first project with ASP .NET GridView (or with anything C#).
I have been struggling with this issue for several days and read many articles and forum posts and answers, as well as tried many solutions but nothing works.

The solution flow:

• Query from SQL Server table on page load into gvPM (grid1) while gvPMgrp (grid2) is not visible.
• Only the first 3 columns (a checkbox, Account number and Account name) are visible, the rest are not visible. The table is very wide so the grid columns are grouped by numbers appended to their header name and in RowDataBound the logic turns visibility of the columns on / off based on the headers' suffix
• The user checks rows to be selected and selects a group number from a drop down list.
• After SELECT button click, the (checked) selected rows are displayed in EDIT mode in a gvPMgrp (grid2) and gvPM (grid1) is not visible.
• On UPDATE button click, I loop in foreach (GridViewRow row in gvPMgrp.Rows) to get the values from the text boxes that were edited and send them as parameters to a stored procedure for update.

Everything works except that this point I always get nulls in the cell. and the following error:
System.NullReferenceException: Object reference not set to an instance of an object

ASPX:
<pre lang="HTML">
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeFile="PMgrp.aspx.cs" Inherits="_PM" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">  
            <h1>Portfolio Monitoring</h1>
                <table>
                    <tr>
                        <th style="text-align: left; line-height: 20px;">
                            Account Number
                        </th>
                        <th style="text-align: left; line-height: 20px;">
                            Account Name
                        </th>
                    </tr>
				    <tr>
					    <td>
						    <asp:TextBox ID="txtAcctNum" Text="Account Number" label="Account Number" runat="server" Width="145px" Height="20px"></asp:TextBox>
					    </td>
					    <td>
						    <asp:TextBox ID="txtAcctName" runat="server" Text="Account Name" Width="145px" Height="20px"></asp:TextBox>					    
                        </td>
                    </tr>
                    <tr>
                        <td>
						    <asp:Button ID="btnSelect" runat="server" Text="Select Account(s)" CommandName="Edit" onclick="btnSelectClick" Width="145px" Height="20px" style="margin-right: 1px"/>
					    </td>                    
                        <td>
						    <asp:Button ID="btnDisplay" runat="server" Text="Display All Accounts" onclick="btnDisplayClick" Width="145px" Height="20px"/>
					    </td>
                    </tr>
                    <tr>
                    <td>
						<asp:Button ID="btnUpdate" runat="server" Text="Update" onclick="btnUpdateClick" Width="145px" Visible = "false" Height="20px"/>					
					</td>
                    <td>
						<asp:Button ID="btnCancel" runat="server" Text="Cancel Edit" onclick="btnCancelClick" Width="145px" Visible = "false" Height="20px"/>
					</td>
                </tr>
                <tr>
                    <td>
					    <asp:DropDownList ID="ddlGrpList" runat="server" DataSourceID="GrpsList"                             
                            DataTextField="GroupName" DataValueField="GroupNum" AutoPostBack="True" 
                            Height="20px" Width="145px" >
                            <asp:ListItem Value="GroupNum">GroupName</asp:ListItem>
                        </asp:DropDownList>
                    
                        <asp:SqlDataSource ID="GrpsList" runat="server" 
                            ConnectionString="Data Source=PARCDBX0001;Initial Catalog=TESTPIN;Integrated Security=True" 
                            ProviderName="System.Data.SqlClient" 
                            SelectCommand="EXEC uspPMgridGrps">    
                        </asp:SqlDataSource>
                        
                    </td>                    
                </tr>
			</table>       
       <div style="width: 100%; height: 700px; overflow: scroll"">
        <asp:GridView 
			ID="gvPM" 
			runat="server" 
			autogeneratecolumns="False" 
			datakeynames="Account_0"    
            onRowDataBound="gvPM_RowDataBound"          
            EnableViewState="true"

            BackColor="White" 
            BorderColor="#CCCCCC" 
			BorderStyle="Solid" 
			BorderWidth="1px" 
			CellPadding="3" 
			HorizontalAlign="Left">			
			
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" VerticalAlign="Top" />
           
            <RowStyle ForeColor="#000066" HorizontalAlign="Left" VerticalAlign="Top" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />			
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
			            
            <Columns>
                <asp:templatefield HeaderText="">
                    <itemtemplate>
                        <asp:checkbox ID="cbSelect" runat="server"></asp:checkbox>
                    </itemtemplate>
                </asp:templatefield>

           		<asp:TemplateField HeaderText="Account_x">
			        <ItemTemplate>
				        <asp:Label Text='<%# Eval("Account_0")%>' runat="server" />
			        </ItemTemplate>
			        <EditItemTemplate>
				        <asp:Label ID="txtAccount_0" Text='<%# Eval("Account_0") %>' runat="server" />
			        </EditItemTemplate>
		        </asp:TemplateField>

                <asp:TemplateField HeaderText="Customer Name CFMAST_x">
			        <ItemTemplate>
				        <asp:Label Text='<%# Eval("Customer_Name_CFMAST_0")%>' runat="server" />
			        </ItemTemplate>
			        <EditItemTemplate>
				        <asp:Label ID="txtCustomer_Name_CFMAST_0" Text='<%# Eval("Customer_Name_CFMAST_0") %>' runat="server" />
			        </EditItemTemplate>
		        </asp:TemplateField>
             
            <asp:TemplateField HeaderText="Cost_to_Liquidate_0" visible="false">
					<ItemTemplate>
						<asp:TextBox Text='<%# Eval("Cost_to_Liquidate_0","{0:c}")%>' runat="server" />
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="txtCost_to_Liquidate_0" Text='<%# Eval("Cost_to_Liquidate_0","{0:c}") %>' runat="server" />
					</EditItemTemplate>
				</asp:TemplateField>

<asp:TemplateField HeaderText="Credit_Rating_040820_0" visible="false">
					<ItemTemplate>
						<asp:TextBox Text='<%# Eval("Credit_Rating_040820_0")%>' runat="server" />
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="txtCredit_Rating_040820_0" Text='<%# Eval("Credit_Rating_040820_0") %>' runat="server" />
					</EditItemTemplate>
				</asp:TemplateField>
				 </Columns>
        </asp:GridView>        
		   <br />
           <br />
           <br />
           <br />
           <br />
           <br />
           <asp:GridView ID="gvPMgrp"
			runat="server" 
			autogeneratecolumns="False" 
			datakeynames="Account_0"    
            onRowDataBound="gvPMgrp_RowDataBound"        
            EnableViewState="true"
            visible="false"
            BackColor="White" 
            BorderColor="#CCCCCC" 
			BorderStyle="Solid" 
			BorderWidth="1px" 
			CellPadding="3" 
			HorizontalAlign="Left">			
			
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" VerticalAlign="Top" />
           
            <RowStyle ForeColor="#000066" HorizontalAlign="Left" VerticalAlign="Top" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />			
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
			            
            <Columns>
           		<asp:TemplateField HeaderText="Account_x">
			        <ItemTemplate>
				        <asp:Label Text='<%# Eval("Account_0")%>' runat="server" />
			        </ItemTemplate>
			        <EditItemTemplate>
				        <asp:Label ID="txtAccount_0" Text='<%# Eval("Account_0") %>' runat="server" />
			        </EditItemTemplate>
		        </asp:TemplateField>

                <asp:TemplateField HeaderText="Customer Name CFMAST_x">
			        <ItemTemplate>
				        <asp:Label Text='<%# Eval("Customer_Name_CFMAST_0")%>' runat="server" />
			        </ItemTemplate>
			        <EditItemTemplate>
				        <asp:Label ID="txtCustomer_Name_CFMAST_0" Text='<%# Eval("Customer_Name_CFMAST_0") %>' runat="server" />
			        </EditItemTemplate>
		        </asp:TemplateField>
             
            <asp:TemplateField HeaderText="Cost_to_Liquidate_0" visible="false">
					<ItemTemplate>
						<asp:TextBox Text='<%# Eval("Cost_to_Liquidate_0","{0:c}")%>' runat="server" />
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="txtCost_to_Liquidate_0" Text='<%# Eval("Cost_to_Liquidate_0","{0:c}") %>' runat="server" />
					</EditItemTemplate>
				</asp:TemplateField>

<asp:TemplateField HeaderText="Credit_Rating_040820_0" visible="false">
					<ItemTemplate>
						<asp:TextBox Text='<%# Eval("Credit_Rating_040820_0")%>' runat="server" />
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="txtCredit_Rating_040820_0" Text='<%# Eval("Credit_Rating_040820_0") %>' runat="server" />
					</EditItemTemplate>
				</asp:TemplateField>
				  </Columns>
        </asp:GridView>       
		</div>
			
    </form>
</body>
</html>



Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Configuration;

public partial class _PM : System.Web.UI.Page
{
    string conStr = @"Data Source=PARCDBX0001;Initial Catalog=TESTPIN; Integrated Security=true";   
    string grp = string.Empty;
    string acctNum = string.Empty;
    string acctName = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {         
            showData();
            btnSelect.Visible = true;
        }        
    }    

    private void showData()
    { 
        string qry = string.Empty;
        
        if ((acctNum.Length > 0) | (acctName.Length > 0)) //Grid for selected rows 
        {
            qry = "dbo.uspPMgetAcctData";
            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = qry;
            cmd.Parameters.Add("@acctNum", SqlDbType.Text).Value = acctNum.Trim();
            cmd.Parameters.Add("@acctName", SqlDbType.Text).Value = acctName.Trim();

            con.Open();
            gvPMgrp.EmptyDataText = "No Records Found";

            gvPM.Visible = false;
            gvPMgrp.Visible = true;
    

            gvPMgrp.DataSource = cmd.ExecuteReader();
            gvPMgrp.DataBind();           
            con.Close();            
        }
        else  //Grid for all rows
        {  
            ddlGrpList.SelectedValue = "x";
            qry = "dbo.uspPMgGetAllData";
            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = qry;

            con.Open();
            gvPM.EmptyDataText = "No Records Found";

            gvPM.Visible = true;
            gvPMgrp.Visible = false;

            gvPM.DataSource = cmd.ExecuteReader();           
            gvPM.DataBind();            
            con.Close();

            btnSelect.Visible = true;
        }
    }
     
    protected void btnUpdateClick(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(conStr);
        con.Open();
        SqlCommand cmd = new SqlCommand("dbo.[uspPMupdtAcctData]", con);
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (GridViewRow row in gvPMgrp.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                string AcctNum = gvPMgrp.DataKeys[row.RowIndex].Value.ToString();
				
				cmd.Parameters.Add("@Account_0", SqlDbType.VarChar).Value = AcctNum;
				cmd.Parameters.AddWithValue("@Cost_to_Liquidate_0", (gvPMgrp.Rows[row.RowIndex].FindControl("txtCost_to_Liquidate_0"))).ToString().Trim();
				cmd.Parameters.AddWithValue("@Credit_Rating_040820_0", (gvPMgrp.Rows[row.RowIndex].FindControl("txtCredit_Rating_040820_0")));
				cmd.ExecuteNonQuery();
            }
        }
        con.Close();
        gvPMgrp.EditIndex = -1;
        showData();
    }

    protected void btnSelectClick(object sender, EventArgs e)
    {
        acctNum = "''";
        
        btnSelect.Visible = false;
        btnUpdate.Visible = true;
        btnCancel.Visible = true;
        
        grp = ddlGrpList.SelectedIndex.ToString().Trim();        

        foreach (GridViewRow row in gvPM.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox cb = (CheckBox)(row.FindControl("cbSelect"));

                if (cb.Checked == true)
                {
                    acctNum += "','" + row.Cells[1].Controls.OfType<Label>().FirstOrDefault().Text;
                }
            }
        }

        string AcctNum  = this.txtAcctNum.Text.Trim();
        string AcctName = this.txtAcctName.Text.Trim();

        if( (!string.IsNullOrEmpty(AcctNum) ) && (AcctNum != "Account Number") )
        {
            if (AcctNum.Contains(","))
            {
                AcctNum = AcctNum.Replace(",", "','");
            }
            acctNum += "','" + AcctNum;
        }

        if (!string.IsNullOrEmpty(AcctName))
        {
            if (AcctName == "Account Name")
            {
                AcctName = "";
            }
        }

        acctName = AcctName;    
        showData();       
    }

    protected void btnDisplayClick(object sender, EventArgs e)
    {
        // Reset groups and accounts info
        grp = "x";
        txtAcctNum.Text = string.Empty;
        txtAcctName.Text = string.Empty;

        btnSelect.Visible = true;
        btnUpdate.Visible = false;
        btnCancel.Visible = false;        
        showData();
    }

    protected void btnCancelClick(object sender, EventArgs e)
    {
        grp = "x";
        btnSelect.Visible = true;
        btnUpdate.Visible = false;
        btnCancel.Visible = false;
        //gvPMgrp.Columns[0].Visible = true;
        gvPMgrp.EditIndex = -1;        
        showData();
    }
    protected void gvPM_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < gvPM.Columns.Count; i++)
        {
            string header = gvPM.Columns[i].HeaderText;
            string cleanHeader = string.Empty;
            string colGrp = string.Empty;

            if ((!string.IsNullOrEmpty(header)) && (header.Length > 1))
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    colGrp = header.Substring(header.Length - 1, 1).Trim();

                    if (colGrp == grp)
                    {
                        gvPM.Columns[i].Visible = true;
                    }
                    else if (grp == "x")
                    {
                        if (i <= 2)
                        {
                            gvPM.Columns[i].Visible = true;
                        }
                        else
                        {
                            gvPM.Columns[i].Visible = false;
                        }
                    }

                    cleanHeader = header.Substring(0, header.Length - 2).Trim().Replace("_", " ");

                    if (cleanHeader.ToLower().Contains(" date "))
                    {
                        cleanHeader += "<br/>(Date: MM/dd/yyyy)";
                    }
                    else if (cleanHeader.ToLower().Contains("cost")
                            || cleanHeader.ToLower().Contains("balance")
                            || ((cleanHeader.ToLower().Contains("value")) && (!cleanHeader.ToLower().Contains("no value")))
                            || cleanHeader.ToLower().Contains("total")
                            )
                    {
                        cleanHeader += "<br/>(Currency: $0.00)";
                    }
                    else if ( (cleanHeader.ToLower().Contains(" to ")) && (!cleanHeader.ToLower().Contains("cost")) )
                    {
                        cleanHeader += "<br/>(Percentage: 0.0%)";
                    }

                    e.Row.Cells[i].Text = cleanHeader;
                }
            }
        }
    }
    protected void gvPMgrp_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {           
            for (int i = 0; i < gvPMgrp.Columns.Count; i++)
            {
            string header = gvPMgrp.Columns[i].HeaderText;
            string cleanHeader = string.Empty;
            string colGrp = string.Empty;

            if ((!string.IsNullOrEmpty(header)) && (header.Length > 1))
            {
                    colGrp = header.Substring(header.Length - 1, 1).Trim();

                    if (colGrp == grp)
                    {
                        gvPMgrp.Columns[i].Visible = true;
                    }
                    else if (grp == "x")
                    {
                        if (i <= 2)
                        {
                            gvPMgrp.Columns[i].Visible = true;
                        }
                        else
                        {
                            gvPMgrp.Columns[i].Visible = false;
                        }
                    }

                    cleanHeader = header.Substring(0, header.Length - 2).Trim().Replace("_", " ");

                    if (cleanHeader.ToLower().Contains(" date "))
                    {
                        cleanHeader += "<br/>(Date: MM/dd/yyyy)";
                    }
                    else if (cleanHeader.ToLower().Contains("cost")
                            || cleanHeader.ToLower().Contains("balance")
                            || ((cleanHeader.ToLower().Contains("value")) && (!cleanHeader.ToLower().Contains("no value")))
                            || cleanHeader.ToLower().Contains("total")
                            )
                    {
                        cleanHeader += "<br/>(Currency: $0.00)";
                    }
                    else if( (cleanHeader.ToLower().Contains(" to ")) && (!cleanHeader.ToLower().Contains("cost")) )
                    {
                        cleanHeader += "<br/>(Percentage: 0.0%)";
                    }

                    e.Row.Cells[i].Text = cleanHeader;
                }
            }
        }
    }
}


What I have tried:

I tried to get viewState into data tables that were initiated in Page_load.
For the sake of shortening this post, I have pasted only a subset of the columns in both grids in the markup, the whole code behind is pasted though.
I also removed all of my failed attempts remnants (they were commented out but it would have appeared to messy)
Something basic is wrong but I can't find it for many days, I hope that someone can pinpoint the issue, any help is much appreciated!
Posted
Updated 3-Jul-20 5:00am

Hello,

This is resolved in another forum I posted:
EditItemTemplate value returns null when looping on rows in the grid | The ASP.NET Forums[^]

Basically, I was missing ID in the ItemTemplate, I was looking for the ID of the EditItemTemplate. What I missed is that the control is not in edit mode at that point so I shouldn't look in EditItemTemplate
   
https://www.c-sharpcorner.com/UploadFile/1e050f/edit-and-update-record-in-gridview-in-Asp-Net/

Try this.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900