I get this exception loading a datagrid:
Exception Details: System.NullReferenceExcept
ion: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Northwind.WebNorthWind.Bin
dGrid() +44
Northwind.WebNorthWind.Pag
e_Load(Obj
ect sender, EventArgs e) +24
System.Web.UI.Control.OnLo
ad(EventAr
gs e) +67
System.Web.UI.Control.Load
Recursive(
) +35
System.Web.UI.Page.Process
RequestMai
n() +731
--------------------------
----------
----------
----------
----------
----------
----------
----------
----------
<%@ Page language="c#" Codebehind="WebNorthWind.a
spx.cs" AutoEventWireup="false" Inherits="Northwind.WebNor
thWind" %>
<%@ import Namespace="System.Web.UI" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScri
pt" content="JavaScript (ECMAScript)">
<meta name="vs_targetSchema" content="
http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body bgcolor="tan">
<form id="WebNorthWind" method="post" runat="server">
<asp:DataGrid id="MyDataGrid" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 104px" runat="server" BorderStyle="Ridge" GridLines="None" BorderWidth="2px" BorderColor="White" BackColor="White" CellPadding="3" CellSpacing="1" AllowPaging="True" AllowSorting="True" PageSize="25" PagerStyle-Mode="NextPrev"
PagerStyle-NextPageText="N
ext" PagerStyle-PrevPageText="P
revious" PagerStyle-HorizontalAlign
="Center" PagerStyle-Position="TopAn
dBottom" DataKeyField="imageid" OnPageIndexChanged="MyData
Grid_PageI
ndexChange
d" OnSortCommand="Sort_Grid" OnDeleteCommand="MyDataGri
d_Delete" OnUpdateCommand="MyDataGri
d_Update" OnCancelCommand="MyDataGri
d_Cancel" OnEditCommand="MyDataGrid_
Edit" AutoGenerateColumns="False
" HorizontalAlign="Left">
<FooterStyle ForeColor="Black" BackColor="#C6C3C6"></Foot
erStyle>
<HeaderStyle Font-Bold="True" ForeColor="#E7E7FF" BackColor="#4A3C8C"></Head
erStyle>
<PagerStyle NextPageText="Next" PrevPageText="Previous" HorizontalAlign="Right" ForeColor="Black" Position="TopAndBottom" BackColor="#C6C3C6"></Page
rStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#9471DE"></Sele
ctedItemSt
yle>
<ItemStyle ForeColor="Black" BackColor="#DEDFDE"></Item
Style>
<Columns>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="<img border=0 src=ok.gif>" CancelText="<img border=0 src=cancel.gif>" EditText="<img border=0 src=edit.gif>"></asp:EditC
ommandColu
mn>
<asp:ButtonColumn Text="<img border=0 src=delete.gif>" CommandName="Delete"></asp
:ButtonCol
umn>
<asp:BoundColumn DataField="imageid" SortExpression="imageid" ReadOnly="True" HeaderText="Image ID"></asp:BoundColumn>
<asp:BoundColumn DataField="displayname" SortExpression="displaynam
e" HeaderText="File Name"></asp:BoundColumn>
<asp:BoundColumn DataField="description1" SortExpression="descriptio
n1" HeaderText="Image Description"></asp:BoundCo
lumn>
<asp:BoundColumn DataField="keywords" SortExpression="keywords" HeaderText="Keywords"></as
p:BoundCol
umn>
<asp:TemplateColumn HeaderText="File" HeaderStyle-HorizontalAlig
n="Center"
ItemStyle-HorizontalAlign=
"Center">
<ItemTemplate>
<img src=<%# DataBinder.Eval(Container.
DataItem,"
finalfilen
ame")%>>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</HTML>
--------------------------
----------
----------
----------
---------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
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 Northwind
{
/// <summary>
/// Summary description for WebNorthWind.
/// </summary>
public class WebNorthWind : System.Web.UI.Page
{
protected System.Web.UI.WebControls.
DataGrid MyDataGrid;
public WebNorthWind()
{
Page.Init += new System.EventHandler(Page_I
nit);
}
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
private void Page_Init(object sender, EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.P
age_Load);
}
#endregion
/// <summary>
/// this function returns dataset of products details
/// </summary>
/// <returns></returns>
private DataSet GetProductData()
{
///this is sql statement which returns records
String SQLStatement="SELECT displayname, description1, keywords, finalfilename, imageid from images ";
///instantiate sql connection and command object
SqlConnection myConnection= new SqlConnection(@"server=loc
alhost;Tru
sted_Conne
ction=true
;database=
storen;");
SqlDataAdapter myCommand = new SqlDataAdapter(SQLStatemen
t,myConnec
tion);
///declare myDataSet as DataSet
DataSet myDataSet;
// mark the Command as s Text
myCommand.SelectCommand.Co
mmandType=
CommandTyp
e.Text;
///create an instance of dataset
myDataSet = new DataSet();
///fill the dataset with returned records
myCommand.Fill(myDataSet, "images");
///finally return dataset
return myDataSet;
}
/// <summary>
/// this function is invoked only when the user clicks edit button
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
///findout the selected item index and bindgrid again
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
/// <summary>
/// when the user clicks cancel button, this function is invoked
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
{
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
/// <summary>
/// this function deletes a record in the dataset
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs E)
{
int imageid =(int)MyDataGrid.DataKeys[
(int)E.Ite
m.ItemInde
x];
String SQLStatement="Delete from images where imageid="+imageid;
SqlConnection myConnection= new SqlConnection(@"server=loc
alhost;Tru
sted_Conne
ction=true
;database=
storen");
SqlCommand myCommand = new SqlCommand(SQLStatement,my
Connection
);
myCommand.CommandType=Comm
andType.Te
xt;
myConnection.Open();
myCommand.ExecuteNonQuery(
);
myConnection.Close();
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
/// <summary>
/// this function updates a record
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
{
int imageid=(int)MyDataGrid.Da
taKeys[(in
t)E.Item.I
temIndex];
string displayname=((TextBox)E.It
em.Cells[3
].Controls
[0]).Text;
string description1=((TextBox)E.I
tem.Cells[
4].Control
s[0]).Text
;
string keywords=((TextBox)E.Item.
Cells[5].C
ontrols[0]
).Text;
string finalfilename=((TextBox)E.
Item.Cells
[6].Contro
ls[0]).Tex
t;
SqlConnection myConnection= new SqlConnection(@"server=loc
alhost;Tru
sted_Conne
ction=true
;database=
storen;");
SqlCommand myCommand = new SqlCommand("loadgrid",myCo
nnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedur
e;
SqlParameter parameterimageid = new SqlParameter("@imageid", SqlDbType.Int, 4);
parameterimageid.Value = imageid;
myCommand.Parameters.Add(p
arameterim
ageid);
// Add Parameters to SPROC
SqlParameter parameterdisplayname = new SqlParameter("@displayname
", SqlDbType.NVarChar, 50);
parameterdisplayname.Value
= displayname;
myCommand.Parameters.Add(p
arameterdi
splayname)
;
SqlParameter parameterdescription1 = new SqlParameter("@description
1", SqlDbType.NVarChar, 3000);
parameterdescription1.Valu
e = description1;
myCommand.Parameters.Add(p
arameterde
scription1
);
SqlParameter parameterkeywords = new SqlParameter("@keywords", SqlDbType.NVarChar, 500);
parameterkeywords.Value = keywords;
myCommand.Parameters.Add(p
arameterke
ywords);
SqlParameter parameterfinalfilename = new SqlParameter("@finalfilena
me", SqlDbType.NVarChar, 50);
parameterfinalfilename.Val
ue = finalfilename;
myCommand.Parameters.Add(p
arameterfi
nalfilenam
e);
myConnection.Open();
myCommand.ExecuteNonQuery(
);
myConnection.Close();
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
/// <summary>
/// this function retrives the data from database and bind datagrid again
/// </summary>
protected void BindGrid()
{
MyDataGrid.DataSource=GetP
roductData
().Tables[
"Products"
].DefaultV
iew;
MyDataGrid.DataBind();
}
/// <summary>
/// this function is for finding the page index whenever datagrid changes the page index
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
protected void MyDataGrid_PageIndexChange
d(object source, System.Web.UI.WebControls.
DataGridPa
geChangedE
ventArgs e)
{
MyDataGrid.CurrentPageInde
x=e.NewPag
eIndex;
BindGrid();
}
/// <summary>
/// this function sorts the dataset based on given criteria
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Sort_Grid(Object sender, DataGridSortCommandEventAr
gs e)
{
DataView dv= new DataView(GetProductData().
Tables["Pr
oducts"]);
dv.Sort= e.SortExpression.ToString(
);
MyDataGrid.DataSource=dv;
MyDataGrid.DataBind();
}
}
--------------------------
----------
----------
----------
----------
----------
-------
Stored Procedure
CREATE Procedure loadgrid
(
@imageid int,
@displayname nvarchar(50),
@description1 nvarchar(3000),
@keywords nvarchar(500),
@finalfilename nvarchar(50)
)
AS
update images
set displayname = @displayname, description1 = @description1, keywords = @keywords, finalfilename = @finalfilename
where imageid = @imageid
GO