DataGridItem.DataItem availability?

L

Laser Lu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it said
"Object reference not set to an instance of an object." How could it happen?
I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by myself, but I
noticed a difference that, the example uses the single-file code (i.e code
was written in the .aspx file) while I wrote my code in the code-behind
mode. So I wonder if this is the reason? But I'm afraid I would be puzzled
if MS says the DataItem property will not be available through code-behind:)
Any help, please?
 
E

Eliyahu Goldin

There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely there is
a problem over there.

Eliyahu
 
L

Laser Lu

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers' on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString() using
Response.Write(), a NullReferenceException occured. But it works fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you please
point me out? Thanks:)
 
E

Eliyahu Goldin

Do you set DataMember property? You have to set it to the name of a table in
your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't sent
attachments.

Eliyahu

Laser Lu said:
And the .aspx file and .cs file is provided in the attachment for your
convenience, if necessary. :)

Laser Lu said:
Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers' on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works fine,
after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


Eliyahu Goldin said:
There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it said
"Object reference not set to an instance of an object." How could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by myself,
but I noticed a difference that, the example uses the single-file code
(i.e code was written in the .aspx file) while I wrote my code in the
code-behind mode. So I wonder if this is the reason? But I'm afraid I
would be puzzled if MS says the DataItem property will not be available
through code-behind:)
Any help, please?
 
L

Laser Lu

I suppose, there is no need to explicity set the DataMember, if there is
only one DataTable exists in the DataSet. The control will automaitcally
find the first DataTable to bind. The previous code I posted withou
specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing the
DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help, please!

BTW: the whole program for Text.aspx was posted below, and just for your
information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs" AutoEventWireup="false"
Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings = new
System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();
((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Eliyahu Goldin said:
Do you set DataMember property? You have to set it to the name of a table
in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't sent
attachments.

Eliyahu

Laser Lu said:
And the .aspx file and .cs file is provided in the attachment for your
convenience, if necessary. :)

Laser Lu said:
Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers'
on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works fine,
after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it
said
"Object reference not set to an instance of an object." How could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by myself,
but I noticed a difference that, the example uses the single-file code
(i.e code was written in the .aspx file) while I wrote my code in the
code-behind mode. So I wonder if this is the reason? But I'm afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
E

Eliyahu Goldin

From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you should
set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

Laser Lu said:
I suppose, there is no need to explicity set the DataMember, if there is
only one DataTable exists in the DataSet. The control will automaitcally
find the first DataTable to bind. The previous code I posted withou
specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing the
DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for your
information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs" AutoEventWireup="false"
Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings = new
System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();
((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Eliyahu Goldin said:
Do you set DataMember property? You have to set it to the name of a table
in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't sent
attachments.

Eliyahu

Laser Lu said:
And the .aspx file and .cs file is provided in the attachment for your
convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers'
on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works fine,
after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it
said
"Object reference not set to an instance of an object." How could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the single-file
code
(i.e code was written in the .aspx file) while I wrote my code in the
code-behind mode. So I wonder if this is the reason? But I'm afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

I have done that in my last code post. :) Maybe, that is not the key point.

Eliyahu Goldin said:
From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you should
set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

Laser Lu said:
I suppose, there is no need to explicity set the DataMember, if there is
only one DataTable exists in the DataSet. The control will automaitcally
find the first DataTable to bind. The previous code I posted withou
specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing the
DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for your
information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs" AutoEventWireup="false"
Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings = new
System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();
((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Eliyahu Goldin said:
Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't
sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for your
convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers'
on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works fine,
after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it
said
"Object reference not set to an instance of an object." How could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the single-file
code
(i.e code was written in the .aspx file) while I wrote my code in
the
code-behind mode. So I wonder if this is the reason? But I'm afraid
I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

Anybody else knows the reason? please help! Thanks a lot!!

Laser Lu said:
Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers' on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString() using
Response.Write(), a NullReferenceException occured. But it works fine,
after I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you please
point me out? Thanks:)


Eliyahu Goldin said:
There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely there
is a problem over there.

Eliyahu
 
E

Eliyahu Goldin

Sorry, missed it.

I think the table name should be "Table1" rather than "Table". Anyway, why
don't you set a breakpoint on the line following the Fill call and check
what is in the dataset?

Eliyahu

Laser Lu said:
I have done that in my last code post. :) Maybe, that is not the key point.

Eliyahu Goldin said:
From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you should
set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

Laser Lu said:
I suppose, there is no need to explicity set the DataMember, if there is
only one DataTable exists in the DataSet. The control will automaitcally
find the first DataTable to bind. The previous code I posted withou
specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing the
DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for your
information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs" AutoEventWireup="false"
Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings = new
System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();

((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't
sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for your
convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from
Customers' on
the Northwind database. Actually, dozens of rows was returned from
the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works
fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to the
currently selected row. However, an exception surprised me that it
said
"Object reference not set to an instance of an object." How could
it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the single-file
code
(i.e code was written in the .aspx file) while I wrote my code in
the
code-behind mode. So I wonder if this is the reason? But I'm afraid
I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

I also did that, but the dataset and dataview both have data contained in
them. The only thing that was strange is that DataItem was not set to any
object reference in the code-behind. But it indeed works for inline code
like <%# Container.DataItem %> in the .aspx file. So strange, I dont' know
why:(

Eliyahu Goldin said:
Sorry, missed it.

I think the table name should be "Table1" rather than "Table". Anyway, why
don't you set a breakpoint on the line following the Fill call and check
what is in the dataset?

Eliyahu

Laser Lu said:
I have done that in my last code post. :) Maybe, that is not the key
point.

Eliyahu Goldin said:
From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you
should set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

I suppose, there is no need to explicity set the DataMember, if there is
only one DataTable exists in the DataSet. The control will automaitcally
find the first DataTable to bind. The previous code I posted withou
specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing the
DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for
your information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs"
AutoEventWireup="false" Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings = new
System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();

((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);
((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't
sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for
your convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from
Customers' on
the Northwind database. Actually, dozens of rows was returned from
the
database. However, when I tried to print out the DataItem.ToString()
using
Response.Write(), a NullReferenceException occured. But it works
fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke
that property to get and display the contents that was bound to
the
currently selected row. However, an exception surprised me that it
said
"Object reference not set to an instance of an object." How could
it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the single-file
code
(i.e code was written in the .aspx file) while I wrote my code in
the
code-behind mode. So I wonder if this is the reason? But I'm
afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
E

Eliyahu Goldin

Ok, I had another look at your code. Does you grid have a header?

In the code

you should be checking e.Item.ItemType. DataItem is applicable only to
ItemType Item and AlternativeItem.

You are likely observing DataItem=null for the Header item.

Eliyahu

Laser Lu said:
I also did that, but the dataset and dataview both have data contained in
them. The only thing that was strange is that DataItem was not set to any
object reference in the code-behind. But it indeed works for inline code
like <%# Container.DataItem %> in the .aspx file. So strange, I dont' know
why:(

Eliyahu Goldin said:
Sorry, missed it.

I think the table name should be "Table1" rather than "Table". Anyway,
why don't you set a breakpoint on the line following the Fill call and
check what is in the dataset?

Eliyahu

Laser Lu said:
I have done that in my last code post. :) Maybe, that is not the key
point.

From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you
should set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

I suppose, there is no need to explicity set the DataMember, if there
is only one DataTable exists in the DataSet. The control will
automaitcally find the first DataTable to bind. The previous code I
posted withou specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing
the DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for
your information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs"
AutoEventWireup="false" Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings =
new System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();

((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);

((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't
sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for
your convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from
Customers' on
the Northwind database. Actually, dozens of rows was returned from
the
database. However, when I tried to print out the
DataItem.ToString() using
Response.Write(), a NullReferenceException occured. But it works
fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file,
likely there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried
to invoke
that property to get and display the contents that was bound to
the
currently selected row. However, an exception surprised me that
it said
"Object reference not set to an instance of an object." How could
it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the single-file
code
(i.e code was written in the .aspx file) while I wrote my code in
the
code-behind mode. So I wonder if this is the reason? But I'm
afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

Thanks for your deeper look at my code:) However, I'm afraid that's also not
the exact reason. I'm sure I had tested the code on Items that are of
ItemType.Item/AlternativeItem. They just don't work, always return null
DateItem. :(

Eliyahu Goldin said:
Ok, I had another look at your code. Does you grid have a header?

In the code

you should be checking e.Item.ItemType. DataItem is applicable only to
ItemType Item and AlternativeItem.

You are likely observing DataItem=null for the Header item.

Eliyahu

Laser Lu said:
I also did that, but the dataset and dataview both have data contained in
them. The only thing that was strange is that DataItem was not set to any
object reference in the code-behind. But it indeed works for inline code
like <%# Container.DataItem %> in the .aspx file. So strange, I dont' know
why:(

Eliyahu Goldin said:
Sorry, missed it.

I think the table name should be "Table1" rather than "Table". Anyway,
why don't you set a breakpoint on the line following the Fill call and
check what is in the dataset?

Eliyahu

I have done that in my last code post. :) Maybe, that is not the key
point.

From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you
should set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

I suppose, there is no need to explicity set the DataMember, if there
is only one DataTable exists in the DataSet. The control will
automaitcally find the first DataTable to bind. The previous code I
posted withou specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing
the DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for
your information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs"
AutoEventWireup="false" Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings =
new System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();

((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new
System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);

((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to dataGrid.Items[0].DataItem?
Typically, it should be in one of the item-related events, like
ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file. Don't
sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for
your convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from
Customers' on
the Northwind database. Actually, dozens of rows was returned from
the
database. However, when I tried to print out the
DataItem.ToString() using
Response.Write(), a NullReferenceException occured. But it works
fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would
you please
point me out? Thanks:)


There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file,
likely there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried
to invoke
that property to get and display the contents that was bound to
the
currently selected row. However, an exception surprised me that
it said
"Object reference not set to an instance of an object." How
could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some
inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the
single-file code
(i.e code was written in the .aspx file) while I wrote my code
in the
code-behind mode. So I wonder if this is the reason? But I'm
afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

Sorry, 'DataItem', not 'DateItem'.:)

Laser Lu said:
Thanks for your deeper look at my code:) However, I'm afraid that's also
not the exact reason. I'm sure I had tested the code on Items that are of
ItemType.Item/AlternativeItem. They just don't work, always return null
DateItem. :(

Eliyahu Goldin said:
Ok, I had another look at your code. Does you grid have a header?

In the code
private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

you should be checking e.Item.ItemType. DataItem is applicable only to
ItemType Item and AlternativeItem.

You are likely observing DataItem=null for the Header item.

Eliyahu

Laser Lu said:
I also did that, but the dataset and dataview both have data contained in
them. The only thing that was strange is that DataItem was not set to any
object reference in the code-behind. But it indeed works for inline code
like <%# Container.DataItem %> in the .aspx file. So strange, I dont'
know why:(

Sorry, missed it.

I think the table name should be "Table1" rather than "Table". Anyway,
why don't you set a breakpoint on the line following the Fill call and
check what is in the dataset?

Eliyahu

I have done that in my last code post. :) Maybe, that is not the key
point.

From the MSDN Library on DataGrid.DataMember property:

---
If the DataSet or DataViewManager contains only one DataTable, you
should set the DataMember to the TableName of that DataTable.
---

Just try this. It doesn't hurt.

Eliyahu

I suppose, there is no need to explicity set the DataMember, if there
is only one DataTable exists in the DataSet. The control will
automaitcally find the first DataTable to bind. The previous code I
posted withou specifying DataMember worked fine in my computer:)

Additionally, I've just followed what you have mentioned, accessing
the DataItem property in item-related events, both ItemCreated and
ItemDataBound. But they still doesn't work, keeping throwing
NullReferenceExceptions in both event handlers. :(

What a pity! I don't know what to do. It really frustrated me! Help,
please!

BTW: the whole program for Text.aspx was posted below, and just for
your information:

/// Test.aspx
<%@ Page language="c#" Codebehind="Test.aspx.cs"
AutoEventWireup="false" Inherits="CEIS.Test" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Test</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dataGrid" runat="server"></asp:datagrid></form>
</body>
</HTML>

/// Test.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CEIS
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test : System.Web.UI.Page
{
protected System.Data.SqlClient.SqlConnection testConnection;
protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
protected System.Data.SqlClient.SqlCommand sqlInsertCommand1;
protected System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
protected System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
protected System.Data.SqlClient.SqlDataAdapter testAdapter;
protected System.Data.DataSet dataSet;
protected System.Web.UI.WebControls.DataGrid dataGrid;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataMember = "Table";
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

// Response.Write(dataGrid.Items[0].DataItem.ToString());
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Configuration.AppSettingsReader configurationAppSettings =
new System.Configuration.AppSettingsReader();
this.testConnection = new System.Data.SqlClient.SqlConnection();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.testAdapter = new System.Data.SqlClient.SqlDataAdapter();
this.dataSet = new System.Data.DataSet();

((System.ComponentModel.ISupportInitialize)(this.dataSet)).BeginInit();
this.dataGrid.ItemCreated += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemCreated);
this.dataGrid.ItemDataBound += new
System.Web.UI.WebControls.DataGridItemEventHandler(this.dataGrid_ItemDataBound);
//
// testConnection
//
this.testConnection.ConnectionString =
((string)(configurationAppSettings.GetValue("testConnection.ConnectionString",
typeof(string))));
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT Customers.* FROM
Customers";
this.sqlSelectCommand1.Connection = this.testConnection;
//
// testAdapter
//
this.testAdapter.DeleteCommand = this.sqlDeleteCommand1;
this.testAdapter.InsertCommand = this.sqlInsertCommand1;
this.testAdapter.SelectCommand = this.sqlSelectCommand1;
this.testAdapter.UpdateCommand = this.sqlUpdateCommand1;
//
// dataSet
//
this.dataSet.DataSetName = "testDataSet";
this.dataSet.Locale = new
System.Globalization.CultureInfo("en-US");
this.Load += new System.EventHandler(this.Page_Load);

((System.ComponentModel.ISupportInitialize)(this.dataSet)).EndInit();

}
#endregion

private void dataGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}

private void dataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
// Response.Write(e.Item.DataItem.ToString());
}
}
}



Do you set DataMember property? You have to set it to the name of a
table in your dataset.

In what part of you code do you refer to
dataGrid.Items[0].DataItem? Typically, it should be in one of the
item-related events, like ItemDataBound or ItemCreated.

If it is not enough, post the relevant part of the .aspx file.
Don't sent attachments.

Eliyahu

And the .aspx file and .cs file is provided in the attachment for
your convenience, if necessary. :)

Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from
Customers' on
the Northwind database. Actually, dozens of rows was returned
from the
database. However, when I tried to print out the
DataItem.ToString() using
Response.Write(), a NullReferenceException occured. But it works
fine, after
I had commented that line of code.
I don't know whether I wrote the code in the correct way, would
you please
point me out? Thanks:)


message
There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file,
likely there
is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried
to invoke
that property to get and display the contents that was bound to
the
currently selected row. However, an exception surprised me that
it said
"Object reference not set to an instance of an object." How
could it
happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some
inessential
descriptions, and a code example. I didn't try that example by
myself,
but I noticed a difference that, the example uses the
single-file code
(i.e code was written in the .aspx file) while I wrote my code
in the
code-behind mode. So I wonder if this is the reason? But I'm
afraid I
would be puzzled if MS says the DataItem property will not be
available
through code-behind:)
Any help, please?
 
L

Laser Lu

Nobody knows that?

Laser Lu said:
Anybody else knows the reason? please help! Thanks a lot!!

Laser Lu said:
Thanks for your response. Here is the code fragment:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
testAdapter.Fill(dataSet);
dataGrid.DataSource = dataSet;
dataGrid.DataBind();

Response.Write(dataGrid.Items[0].DataItem.ToString()); // A
NullReferenceException will be thrown here!
}

The testAdapter executes an SelectCommand as 'select * from Customers' on
the Northwind database. Actually, dozens of rows was returned from the
database. However, when I tried to print out the DataItem.ToString()
using Response.Write(), a NullReferenceException occured. But it works
fine, after I had commented that line of code.
I don't know whether I wrote the code in the correct way, would you
please point me out? Thanks:)


Eliyahu Goldin said:
There is no difference where the code is.

Post the relevant fragment from the code and the .aspx file, likely
there is a problem over there.

Eliyahu

Hi, all,
I was tangled by the DataGridItem.DataItem property. I tried to
invoke that property to get and display the contents that was bound to
the currently selected row. However, an exception surprised me that it
said "Object reference not set to an instance of an object." How could
it happen? I have set the data source, and called the DataBind().
I looked up the MSDN documents, and just find some inessential
descriptions, and a code example. I didn't try that example by myself,
but I noticed a difference that, the example uses the single-file code
(i.e code was written in the .aspx file) while I wrote my code in the
code-behind mode. So I wonder if this is the reason? But I'm afraid I
would be puzzled if MS says the DataItem property will not be available
through code-behind:)
Any help, please?
 
P

pedaammulu

Hi,


The following code should work.

Dim myConnection As SqlConnection = New SqlConnection("Data
Source=SYS1;Integrated Security=SSPI;Initial Catalog=NorthWind")
Const strSQL As String = "SELECT CustomerID, CompanyName,
ContactName FROM Customers"
Dim myAdapter As SqlDataAdapter = New SqlDataAdapter(strSQL,
myConnection)
Protected WithEvents Mygrid_ID As
System.Web.UI.WebControls.DataGrid
Dim dstcustomers As New DataSet()

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

If Not IsPostBack() Then
BindDataGrid()
End If
Response.Write("dfgg")
Response.Write(Mygrid_ID.Items(0).Cells(0).Text)
End Sub

Sub BindDataGrid()
myConnection.Open()
myAdapter.Fill(dstcustomers, "Customers")
Mygrid_ID.DataSource = dstcustomers
Mygrid_ID.DataBind()
End Sub

End Class


Regards
Bhar
Books for programmers
http://www.vkinfotek.com
 
L

Laser Lu

Thanks for your response!
You suggested an alternative way to get the data by retrieving the text in
grid cells and parsing it. :)
It works, but doesn't seem like the elegant way to get the bound data.:(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top