Click here to Skip to main content
15,883,731 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,
I am now to website development. I used a example posted by someone. However, after compilation my editable GridView cannot update, but deleting, editing, Inserting data all work well. I think the problem should be on the "DataBound" in its .cs file.

I want let this GridView works on Updating data in each row to SQL table. When I click the Update button, I get this error message: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Any one can help me out?

Now I post my code for your convenience.
code in Default.cs file
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class GridViewInsertEditUpdateDelete : System.Web.UI.Page
{

    CustomersCls customer = new CustomersCls();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            FillCustomerInGrid();
    }

    private void FillCustomerInGrid()
    {
        DataTable dtCustomer = customer.Fetch();

        if (dtCustomer.Rows.Count > 0)
        {
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();
        }
        else
        {
            dtCustomer.Rows.Add(dtCustomer.NewRow());
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();

            int TotalColumns = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GridView1.Rows[0].Cells[0].Text = "No Record Found";
        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtNewOrderID = (TextBox)GridView1.FooterRow.FindControl("txtNewOrderID");
            DropDownList cmbNewPart = (DropDownList)GridView1.FooterRow.FindControl("cmbNewPart");
            DropDownList cmbNewStage = (DropDownList)GridView1.FooterRow.FindControl("cmbNewStage");
            DropDownList cmbNewOperation = (DropDownList)GridView1.FooterRow.FindControl("cmbNewOperation");
            TextBox txtNewUpdateDate = (TextBox)GridView1.FooterRow.FindControl("txtNewUpdateDate");
            TextBox txtNewUpdater = (TextBox)GridView1.FooterRow.FindControl("txtNewUpdater");
            customer.Insert(Convert.ToInt32(txtNewOrderID.Text), cmbNewPart.SelectedValue, 
                cmbNewStage.SelectedValue, cmbNewOperation.SelectedValue, 
                txtNewUpdateDate.Text, Convert.ToInt32(txtNewUpdater.Text));
            FillCustomerInGrid();
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
   
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        FillCustomerInGrid();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        customer.Delete(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()));
        FillCustomerInGrid();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        FillCustomerInGrid();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        
        TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
        DropDownList cmbPart = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbPart");
        DropDownList cmbStage = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbStage");
        DropDownList cmbOperation = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbOperation");
        TextBox txtUpdateDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateDate");
        TextBox txtUpdater = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdater");

        customer.Update(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()), 
            Convert.ToInt32(txtOrderID.Text), cmbPart.SelectedValue, 
            cmbStage.SelectedValue, cmbOperation.SelectedValue, 
            txtUpdateDate.Text, Convert.ToInt32(txtUpdater.Text));
        GridView1.EditIndex = -1;
        FillCustomerInGrid();
       }
}


And the code in Default.aspx
<<pre lang="xml">%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GridViewInsertEditUpdateDelete" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="OrderID"  SortExpression="OrderID">
<EditItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("OrderID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewOrderID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("OrderID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part">
<EditItemTemplate>
  <asp:DropDownList ID="cmbPart" runat="server" SelectedValue='<%# Eval("Part") %>'>
    <asp:ListItem Value="Top Rail" Text="Top Rail"></asp:ListItem>
    <asp:ListItem Value="Bottom Rail" Text="Bottom Rail"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="lbPart" runat="server" Text='<%# Eval("Part") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewPart" runat="server" >
    <asp:ListItem Selected="True" Value="Top Rail" Text="Top Rail"></asp:ListItem>
    <asp:ListItem Value="Bottom Rail" Text="Bottom Rail"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stage">
<EditItemTemplate>
  <asp:DropDownList ID="cmbStage" runat="server" SelectedValue='<%# Eval("Stage") %>'>
    <asp:ListItem Value="Design" Text="Design"></asp:ListItem>
    <asp:ListItem Value="Manufacturing" Text="Manufacturing"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="lbStage" runat="server" Text='<%# Eval("Stage") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewStage" runat="server" >
    <asp:ListItem Selected="True" Value="Design" Text="Design"></asp:ListItem>
    <asp:ListItem Value="Manufacturing" Text="Manufacturing"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Operation">
<EditItemTemplate>
  <asp:DropDownList ID="cmbOperation" runat="server" SelectedValue='<%# Eval("Operation") %>'>
    <asp:ListItem Value="Machining" Text="Machining"></asp:ListItem>
    <asp:ListItem Value="Coloring" Text="Coloring"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="lbOperation" runat="server" Text='<%# Eval("Operation") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewOperation" runat="server" >
    <asp:ListItem Selected="True" Value="Machining" Text="Machining"></asp:ListItem>
    <asp:ListItem Value="Coloring" Text="Coloring"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateDate">
<EditItemTemplate>
  <asp:TextBox ID="txtUpdateDate" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewUpdateDate" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("UpdateDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Updater"> <EditItemTemplate>
  <asp:TextBox ID="txtUpdater" runat="server" Text='<%# Eval("Updater") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewUpdater" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("Updater") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
        <br />
        <br />
        <br />
        </div>
    </form>
</body>
</html>



The CustomersCls.cs code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for ClsCustomer
/// </summary>
public class CustomersCls
{

    private string cnstr = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
    private string sql;

    public CustomersCls()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public void Insert(int OrderID, string Part, string Stage, string Operation, string UpdateDate, int Updater)
    {
        string sql = "Insert Into Progress (OrderID, Part, Stage, Operation, UpdateDate, Updater) Values ('" + OrderID + "', '" + Part
            + "' , '" + Stage + "', '" + Operation + "', '" + UpdateDate + "', '" + Updater + "')";
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

    public DataTable Fetch()
    {
        string sql = "Select * From Progress";
        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }




    public void Update(int CustomerCode, int OrderID, string Part, string Stage, string Operation, string UpdateDate, int Updater)
    {
        string sql = "UPDATE Progress SET OrderID = '" + OrderID + "', Part = '" + Part 
            + "', Stage= '" + Stage + "', Operation = '" + Operation 
            + "', UpdateDate = '" + UpdateDate + "', Updater = '" + Updater
            + "' Where Code=" + CustomerCode;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

    public void Delete(int CustomerCode)
    {
        string sql = "Delete Progress Where Code=" + CustomerCode;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

//    public DataTable FetchCustomerType()
//    {
//        string sql = "Select Type From Progress";
//        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
//        DataTable dt = new DataTable();
//        da.Fill(dt);
//       return dt;
//    }


}
Posted
Updated 21-Jul-11 0:23am
v2
Comments
Toniyo Jackson 21-Jul-11 5:51am    
What error you are getting?
Bomiao 21-Jul-11 6:16am    
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

You have used TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID"); in GridView1_RowUpdating event. But you don't have txtOrderID control in design. So, you are getting System.NullReferenceException: Object reference not set to an instance of an object error. Please correct that.
 
Share this answer
 
if it is a nullreference any of the next statements fails:

TextBox txtOrderID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOrderID");
        DropDownList cmbPart = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbPart");
        DropDownList cmbStage = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbStage");
        DropDownList cmbOperation = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbOperation");
        TextBox txtUpdateDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateDate");
        TextBox txtUpdater = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdater")

If FindControl cannot find the control it's value will be NULL.

Debug this part of code and add Watch items to see which one is NULL
 
Share this answer
 
GridView1.DataKeys[e.RowIndex].Value.ToString())

Do changes hope you will find your solution
 
Share this answer
 

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