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

LVL 1
chris_desboroughAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gazzzzzzerCommented:
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
0
Kevin CrossChief Technology OfficerCommented:
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.
0
iUsernameCommented:
Maybe the datatable you're sending has no rows... ? (dt.Rows == null)
0
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Kevin CrossChief Technology OfficerCommented:
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.
0
Kevin CrossChief Technology OfficerCommented:
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.
0
guru_samiCommented:
I think you are taking hard way...
You have a GridView with a delete button to delete a record... so instead of OnClick="btnDelete_Click" use  CommandName="Delete"
<ItemTemplate>
  <asp:Button ID="btnDelete" runat="server" Text="Del" CommandArgument='<%#DataBinder.Eval(Container,"DataItem.id")%>'  CommandName="Delete"   />
                                </ItemTemplate>

Now your RowDeleting should look like below:
protected void ItemInOrder_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dt.Rows[e.RowIndex].Delete();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

I don't see a need of FindRow and other stuff....

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chris_desboroughAuthor Commented:
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.
0
chris_desboroughAuthor Commented:
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();
    }
0
guru_samiCommented:
GridViewRow gvr = ItemInOrder.Rows[e.RowIndex];
lblDeleted.Text = gvr.Cells[1].Text; //make sure you pass correct index
0
chris_desboroughAuthor Commented:
Terrific thanks..
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.