Link to home
Start Free TrialLog in
Avatar of chris_desborough
chris_desboroughFlag for Australia

asked on

Object reference not set to an instance of an object.

Cannot resolve the error I'm receiving - Object reference not set to an instance of an object - for "dt.Rows.Count" in the FindRow method.
   

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
 
public partial class Default3 : System.Web.UI.Page
{
 
    static DataTable dt = null;
    static DataRow dr = null;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session["counter"] = 0;  // used to increment the 'id' Datatable value
 
            dt = new DataTable();
 
            dt.Columns.Add("id");
            dt.Columns.Add("qtyordered");
            dt.Columns.Add("itemdesc");
            dt.Columns.Add("unitofissue");
            dt.Columns.Add("itemno");
 
            ItemInOrder.DataSource = dt;
            ItemInOrder.DataBind();
 
            lblItemsInOrder.Text = "0";
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        int id = int.Parse(b.CommandArgument);
        DeletedRows.Add(id);
        ItemInOrder.DeleteRow(id);
    }
    protected void ItemInOrder_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt = (DataTable)ItemInOrder.DataSource;
        foreach (int i in DeletedRows)
        {
            DataRow dr = FindRow(dt, i);
            dt.Rows.Remove(dr);
        }
        ItemInOrder.DataSource = dt;
        ItemInOrder.DataBind();
    }
    private DataRow FindRow(DataTable dt, int id)
    {
      
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow row = dt.Rows[i];
            int rowId = int.Parse(row["id"].ToString());
            if (rowId == id)
                return row;
        }
        return dr;
    }
    public ArrayList DeletedRows
    {
        get
        {
            if (Session["DELETED_ROW_COLLECTION"] == null)
                Session["DELETED_ROW_COLLECTION"] = new ArrayList();
            return (ArrayList)Session["DELETED_ROW_COLLECTION"];
        }
    }
 
    protected void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.NewSelectedIndex];
 
    }
 
    protected void SqlItemList_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
 
    }
 
    protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
    {
 
        // Get the currently selected row using the SelectedRow property.
        GridViewRow row = GridView1.SelectedRow;
 
        // Get the invisible gridview column Item_ID value  
        string idText = ((Label)GridView1.SelectedRow.FindControl("lblItemID")).Text;
 
        // Get the value of the textbox qty template field
        string qtyText = ((TextBox)GridView1.SelectedRow.FindControl("QtyToAdd")).Text;
  
        int maxOrderQty = Convert.ToInt32(row.Cells[6].Text);
        int orderQty = Convert.ToInt32(qtyText);
 
        if (orderQty > maxOrderQty)
        {
            // do something clever
            Response.Write("<script>confirm('Quantity you ordered exceeds the maximum order quantity for this item.')</script>");
            return;
        }
 
        // Insert data into the temp datatable
 
        DataRow dr = dt.NewRow();
 
        int @counter = Convert.ToInt32(Session["counter"]) + 1;
 
        dr["id"] = @counter;
        dr["qtyordered"] = qtyText;
        dr["itemdesc"] = row.Cells[2].Text;
        dr["unitofissue"] = row.Cells[3].Text;
        dr["itemno"] = row.Cells[5].Text;
 
        dt.Rows.Add(dr);
 
        ItemInOrder.DataSource = dt;
        ItemInOrder.DataBind();
 
        Session["counter"] = @counter; 
 
        lblItemsInOrder.Text = @counter.ToString();
 
    }
}
==========================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3"
    EnableEventValidation="false" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            color: #FFFFFF;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="SqlCategoriesList" runat="server" ConnectionString="<%$ ConnectionStrings:docstoresConnectionString %>"
            SelectCommand="SELECT [Category] FROM [Category] WHERE ([Category] &lt;&gt; @Category) ORDER BY [Category]">
            <SelectParameters>
                <asp:Parameter DefaultValue="ALL ITEMS" Name="Category" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlItemList" runat="server" ConnectionString="<%$ ConnectionStrings:docstoresConnectionString %>"
            OnSelecting="SqlItemList_Selecting" SelectCommand="SELECT [Item_ID], [Item_Description], [Item_UnitofIssue], [Item_Image], [Item_ItemNo], [Item_MaxOrderQty] FROM [Items] WHERE (([Item_Active] = @Item_Active) AND ([Item_Category] = @Item_Category))">
            <SelectParameters>
                <asp:Parameter DefaultValue="true" Name="Item_Active" Type="Boolean" />
                <asp:ControlParameter ControlID="ddlCategory" Name="Item_Category" PropertyName="SelectedValue"
                    Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <table style="width: 100%;">
            <tr>
                <td bgcolor="#0033CC">
                    <span class="style1">Select Category</span>
                    <asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" DataSourceID="SqlCategoriesList"
                        DataTextField="Category" DataValueField="Category">
                    </asp:DropDownList>
                </td>
                <td>
                    &nbsp;
                </td>
                <td bgcolor="#0033CC" class="style1">
                    Order Total =
                    <asp:Label ID="lblItemsInOrder" runat="server" Text="Label"></asp:Label>
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Item_ID"
                        DataSourceID="SqlItemList" EmptyDataText=".. No items in this category" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
                        OnSelectedIndexChanging="GridView1_SelectedIndexChanging">
                        <Columns>
                            <asp:CommandField ButtonType="Button" SelectText="Add" ShowSelectButton="True" />
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:TextBox ID="QtyToAdd" runat="server" Width="25px"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="Item_Description" HeaderText="Description" SortExpression="Item_Description" />
                            <asp:BoundField DataField="Item_UnitofIssue" HeaderText="Unit of Issue" SortExpression="Item_UnitofIssue" />
                            <asp:BoundField DataField="Item_Image" HeaderText="Image" SortExpression="Item_Image" />
                            <asp:BoundField DataField="Item_ItemNo" HeaderText="Item No" SortExpression="Item_ItemNo" />
                            <asp:BoundField DataField="Item_MaxOrderQty" HeaderText="Max Qty" SortExpression="Item_MaxOrderQty" />
                            <asp:TemplateField HeaderText="ID" Visible="False">
                                <ItemTemplate>
                                    <asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_ID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
                <td>
                    &nbsp;
                </td>
                <td valign="top">
                    <asp:GridView ID="ItemInOrder" runat="server" OnRowDeleting="ItemInOrder_RowDeleting"
                        EmptyDataText=".. no items in order">
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:Button ID="btnDelete" runat="server" Text="Del" CommandArgument='<%#DataBinder.Eval(Container,"DataItem.id")%>'
                                        OnClick="btnDelete_Click" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td valign="top">
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
                <td valign="top">
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Open in new window

Avatar of gazzzzzzer
gazzzzzzer
Flag of United Kingdom of Great Britain and Northern Ireland image

To start with, try adding a brreakpoint in the FindRow function and check if the dt value being passed is null, maybe line 45 is not actually initialising the variable.
If this is not null, while still debugging, inspect the dt object and check the Rows property is returning a valid value.
Post your finding and I will try and help more
Avatar of Kevin Cross
That would indicate that dt is not set to an instance of an object (Nothing) at the point it is used in FindRow as an Object.  

From what I saw in the code, you are setting a local dt variable from ItemInOrder.DataSource.  You have dt defined as a global variable.  Try commenting out line 45 and see if that is the problem AND/OR put in code to handle if dt passed to FindRow method IsNothing() before trying to use it.
Avatar of iUsername
iUsername

Maybe the datatable you're sending has no rows... ? (dt.Rows == null)
Good points, gazzzzzzer.  I was thinking more VB.NET, in C# you definitely looking for NULL not NOTHING.  And from the line of code getting the error, it is definitely possible that dt is a proper object, but dt.Rows is what is null so debug with break points as suggested should help narrow down which case you are experiencing.
As a matter of fact, the code you posted shows you creating the data table with column headings but no actual data so there are no rows in your data table given the code above.
ASKER CERTIFIED SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chris_desborough

ASKER

Hi guru sami,

Your solution works great - problem solved. The binding in the method should be to the ItemInOrder datatable though.

mwvisa1/gazzzzer - thanks for you comments. Rows were actually added to the ItemInOrder datatable in the GridView1_SelectedIndexChanged method.
Just one final thing. How can I pull out the row cell values of the deleted row and assign it to a label?

protected void ItemInOrder_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dt.Rows[e.RowIndex].Delete();
       
        lblDeleted.Text = ??? <<<<-------------------------

        ItemInOrder.DataSource = dt;
        ItemInOrder.DataBind();
    }
GridViewRow gvr = ItemInOrder.Rows[e.RowIndex];
lblDeleted.Text = gvr.Cells[1].Text; //make sure you pass correct index
Terrific thanks..