Hi,
Myself Vishwasdeep. I am doing a project work on asp.net. I am getting an error/exception on my code.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
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.Data.Sql;
using System.Data.SqlClient;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("id", typeof(string));
            dt.Columns.Add(dc);
            DataColumn dc1 = new DataColumn("name", typeof(string));
            dt.Columns.Add(dc1);

            foreach (GridViewRow grow in GridView1.Rows)
            {
                
               CheckBox cbox = (CheckBox)grow.FindControl("cbox"); 
                if (cbox.Checked == true) // i am getting exception here ,Object reference not set to an instance of an object.//
                {
                    DataRow dr = dt.NewRow();
                    dr["id"] = grow.Cells[0].Text;
                    dr["name"] = grow.Cells[1].Text;
                    dt.Rows.Add(dr);
                }
            }
            ds.Tables.Add(dt);
            GridView2.DataSource = ds;
            GridView2.DataBind();
        }
    }
}

Plz anyone can help to solve this exception as soon as possible.
Regards,
Vishwasdeep

Where are you making que the bind of the GridView1?

1. NullReferenceException is raised when code tries to access something which isn't there. In the code given you are creating a checkbox type variable and assigning it to the checkbox type found in the current row of gridview. Now if for some reason if your gridview row is empty or checkbox is not there/checkbox couldn't be found, then your variable is assigned to null. Next line of code tries to access a property of the variable which is actually null and hence comes the sweet exception :) :)

2. If you check the checkbox before accessing its property then you can possibly avoid the exception

CheckBox cbox = (CheckBox)grow.FindControl("cbox"); 
if(cbox!=null)
{
  if (cbox.Checked == true)
  {
      DataRow dr = dt.NewRow();
      /*your following lines of code.....*/
  }
}

3. What exactly is causing the checkbox to be null, is difficult for me to figure out from the code given...some other more experienced people would definitely have a better answer for that.

Imo, it could be the gridview losting its values on postback... but I agree with ckchaudhary, with only this code It's dificult to give you some help

if null exception error occurs, then most of the times then the previous line of code does not get a value.

For a new programmer, I would say check whether you have enabled viewstate in the grid view.

What i am trying to do is,i created a grid view with "id","name" as field and i used checkbox as template field in grid view. Now when i check a chechbox,that checked row should comes to a new grid view on button click. Thats what i am trying to do in my code.

can you show the code where you are binding the data of that gridview?

can you show the code where you are binding the data of that gridview?

I am using SQLDATASOURCE for data binding with gridview

is the viewstate enable on the gridview?

can you show the code where you are binding the data of that gridview?

I am using SQLDATASOURCE for data binding with gridview

is the viewstate enable on the gridview?

Yes,it is enabled.

Yes,it is enabled.

That's weird because your code seems to be right.
Can you post the aspx code just to check one thing?

That's weird because your code seems to be right.
Can you post the aspx code just to check one thing?

Sure,here is the source code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<!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="id" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" 
                    SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:abcdConnectionString %>" 
            SelectCommand="SELECT [id], [name] FROM [info1]"></asp:SqlDataSource>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Sure,here is the source code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<!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="id" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" 
                    SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:abcdConnectionString %>" 
            SelectCommand="SELECT [id], [name] FROM [info1]"></asp:SqlDataSource>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Found it :icon_cheesygrin:

As I suspected, you didn't set ID to the checkbox.
You can see here where you put your template field

<asp:TemplateField>
 <ItemTemplate>
  <asp:CheckBox ID="CheckBox1" runat="server" />
 </ItemTemplate>
 </asp:TemplateField>

The ID is "Checkbox1", but in the code behind you are looking for a checkbox with a diferent ID

CheckBox cbox = (CheckBox)grow.FindControl("cbox");

Just change the ID in the template fiel to "cbox" and that should work.

Found it :icon_cheesygrin:

As I suspected, you didn't set ID to the checkbox.
You can see here where you put your template field

<asp:TemplateField>
 <ItemTemplate>
  <asp:CheckBox ID="CheckBox1" runat="server" />
 </ItemTemplate>
 </asp:TemplateField>

The ID is "Checkbox1", but in the code behind you are looking for a checkbox with a diferent ID

CheckBox cbox = (CheckBox)grow.FindControl("cbox");

Just change the ID in the template fiel to "cbox" and that should work.

It worked. Thanks a lot :)

Found it :icon_cheesygrin:

As I suspected, you didn't set ID to the checkbox.
You can see here where you put your template field

<asp:TemplateField>
 <ItemTemplate>
  <asp:CheckBox ID="CheckBox1" runat="server" />
 </ItemTemplate>
 </asp:TemplateField>

The ID is "Checkbox1", but in the code behind you are looking for a checkbox with a diferent ID

CheckBox cbox = (CheckBox)grow.FindControl("cbox");

Just change the ID in the template fiel to "cbox" and that should work.

As you know in this code,when i check the items in gridview1 that checked row goes to gridview2. Now i want to save that gridview2 into database (SQL). How to do that? Pls help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.