Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Object reference not set to an instance of an object.

Posted on 2009-07-02
10
Medium Priority
?
1,848 Views
Last Modified: 2012-05-07
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

0
Comment
Question by:chris_desborough
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 5

Expert Comment

by:gazzzzzzer
ID: 24768393
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
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 24768395
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
 
LVL 5

Expert Comment

by:iUsername
ID: 24768412
Maybe the datatable you're sending has no rows... ? (dt.Rows == null)
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 60

Expert Comment

by:Kevin Cross
ID: 24768417
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
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 24768431
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
 
LVL 41

Accepted Solution

by:
guru_sami earned 800 total points
ID: 24768549
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
 
LVL 1

Author Comment

by:chris_desborough
ID: 24768657
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
 
LVL 1

Author Comment

by:chris_desborough
ID: 24768690
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
 
LVL 41

Expert Comment

by:guru_sami
ID: 24768789
GridViewRow gvr = ItemInOrder.Rows[e.RowIndex];
lblDeleted.Text = gvr.Cells[1].Text; //make sure you pass correct index
0
 
LVL 1

Author Comment

by:chris_desborough
ID: 24768863
Terrific thanks..
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Loops Section Overview

877 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question