[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.2

null ref. exception loading Datagrid

Asked by dprasad in Programming for ASP.NET

I get this exception loading a datagrid:

 Exception Details: System.NullReferenceException: 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.BindGrid() +44
   Northwind.WebNorthWind.Page_Load(Object sender, EventArgs e) +24
   System.Web.UI.Control.OnLoad(EventArgs e) +67
   System.Web.UI.Control.LoadRecursive() +35
   System.Web.UI.Page.ProcessRequestMain() +731

----------------------------------------------------------------------------------------------------------
<%@ Page language="c#" Codebehind="WebNorthWind.aspx.cs" AutoEventWireup="false" Inherits="Northwind.WebNorthWind" %>
<%@ 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_defaultClientScript" 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="Next" PagerStyle-PrevPageText="Previous" PagerStyle-HorizontalAlign="Center" PagerStyle-Position="TopAndBottom" DataKeyField="imageid" OnPageIndexChanged="MyDataGrid_PageIndexChanged" OnSortCommand="Sort_Grid" OnDeleteCommand="MyDataGrid_Delete" OnUpdateCommand="MyDataGrid_Update" OnCancelCommand="MyDataGrid_Cancel" OnEditCommand="MyDataGrid_Edit" AutoGenerateColumns="False" HorizontalAlign="Left">
                    <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle>
                    <HeaderStyle Font-Bold="True" ForeColor="#E7E7FF" BackColor="#4A3C8C"></HeaderStyle>
                    <PagerStyle NextPageText="Next" PrevPageText="Previous" HorizontalAlign="Right" ForeColor="Black" Position="TopAndBottom" BackColor="#C6C3C6"></PagerStyle>
                    <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#9471DE"></SelectedItemStyle>
                    <ItemStyle ForeColor="Black" BackColor="#DEDFDE"></ItemStyle>
                    <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:EditCommandColumn>
                         <asp:ButtonColumn Text="<img border=0 src=delete.gif>" CommandName="Delete"></asp:ButtonColumn>
                         <asp:BoundColumn DataField="imageid" SortExpression="imageid" ReadOnly="True" HeaderText="Image ID"></asp:BoundColumn>
                         <asp:BoundColumn DataField="displayname" SortExpression="displayname" HeaderText="File Name"></asp:BoundColumn>
                         <asp:BoundColumn DataField="description1" SortExpression="description1" HeaderText="Image Description"></asp:BoundColumn>
                         <asp:BoundColumn DataField="keywords" SortExpression="keywords" HeaderText="Keywords"></asp:BoundColumn>
                         <asp:TemplateColumn HeaderText="File" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                   <ItemTemplate>
                              <img src=<%# DataBinder.Eval(Container.DataItem,"finalfilename")%>>
                               </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_Init);
          }

          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.Page_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=localhost;Trusted_Connection=true;database=storen;");
               SqlDataAdapter myCommand = new SqlDataAdapter(SQLStatement,myConnection);

               ///declare myDataSet as DataSet
               DataSet myDataSet;

               // mark the Command as s Text
               myCommand.SelectCommand.CommandType=CommandType.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.Item.ItemIndex];
               String SQLStatement="Delete from images where imageid="+imageid;

     SqlConnection myConnection= new SqlConnection(@"server=localhost;Trusted_Connection=true;database=storen");
               SqlCommand myCommand = new SqlCommand(SQLStatement,myConnection);



               myCommand.CommandType=CommandType.Text;

               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.DataKeys[(int)E.Item.ItemIndex];
               string displayname=((TextBox)E.Item.Cells[3].Controls[0]).Text;
               string description1=((TextBox)E.Item.Cells[4].Controls[0]).Text;
               string keywords=((TextBox)E.Item.Cells[5].Controls[0]).Text;
               string finalfilename=((TextBox)E.Item.Cells[6].Controls[0]).Text;


SqlConnection myConnection= new SqlConnection(@"server=localhost;Trusted_Connection=true;database=storen;");
               SqlCommand myCommand = new SqlCommand("loadgrid",myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;


SqlParameter parameterimageid = new SqlParameter("@imageid", SqlDbType.Int, 4);
            parameterimageid.Value = imageid;
            myCommand.Parameters.Add(parameterimageid);



            // Add Parameters to SPROC
            SqlParameter parameterdisplayname = new SqlParameter("@displayname", SqlDbType.NVarChar, 50);
            parameterdisplayname.Value = displayname;
            myCommand.Parameters.Add(parameterdisplayname);




            SqlParameter parameterdescription1 = new SqlParameter("@description1", SqlDbType.NVarChar, 3000);
            parameterdescription1.Value = description1;
            myCommand.Parameters.Add(parameterdescription1);

            SqlParameter parameterkeywords = new SqlParameter("@keywords", SqlDbType.NVarChar, 500);
            parameterkeywords.Value = keywords;
            myCommand.Parameters.Add(parameterkeywords);

SqlParameter parameterfinalfilename = new SqlParameter("@finalfilename", SqlDbType.NVarChar, 50);
            parameterfinalfilename.Value = finalfilename;
            myCommand.Parameters.Add(parameterfinalfilename);            

               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=GetProductData().Tables["Products"].DefaultView;
               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_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
          {
               MyDataGrid.CurrentPageIndex=e.NewPageIndex;
               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, DataGridSortCommandEventArgs e)
          {

               DataView dv= new DataView(GetProductData().Tables["Products"]);
               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
 
Loading Advertisement...
 
[+][-]07/18/04 10:19 PM, ID: 11580882Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zone: Programming for ASP.NET
Sign Up Now!
Solution Provided By: tovvenki
Participating Experts: 2
Solution Grade: A
 
[+][-]07/18/04 09:13 PM, ID: 11580642Assisted Solution

Assisted solutions are selected by the member who asked the question as a comment that contributed to their question's solution.

Start your 30-day free trial to view this Assisted Solution or ask the Experts your question.

 
[+][-]07/18/04 09:40 PM, ID: 11580725Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-92