Solved

Object reference not set to an instance of an object.

Posted on 2009-07-02
10
1,613 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
Comment Utility
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 59

Expert Comment

by:Kevin Cross
Comment Utility
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
Comment Utility
Maybe the datatable you're sending has no rows... ? (dt.Rows == null)
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
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 59

Expert Comment

by:Kevin Cross
Comment Utility
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 41

Accepted Solution

by:
guru_sami earned 200 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Terrific thanks..
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now