0

I have a GridView on an ASP. NET web form which is displaying some information from a table in a SQL database. I also have some buttons to delete, update and add new data. However, my delete button doesn't work. I keep getting the error "Object reference not set to an instance of an object."

I will post the function below with the data in the table. Can anyone assist me, please?

 <asp:GridView ID="gvFarmer" runat="server"
        BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="5" style="margin-right: 58px"
        CellSpacing="1" GridLines="None" AutoGenerateColumns="false" Height="166px" Width="692px" ShowFooter="true" ShowHeaderWhenEmpty="true" 
        OnRowCommand="gvFarmer_RowCommand" OnRowEditing="gvFarmer_RowEditing" OnRowCancelingEdit="gvFarmer_RowCancelingEdit" OnRowUpdating="gvFarmer_RowUpdating" OnRowDeleting="gvFarmer_RowDeleting">


        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
        <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
        <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#594B9C" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#33276A" />

        <Columns> <%--Colums are created here --%>

                                        <%-- COLUMN 1--%>

             <%-- Creation of template field to hold column names and information for a table--%>
            <asp:TemplateField HeaderText="Farmer ID"> <%-- here the filed is created--%>
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("Farmer_Id") %>' runat="server"></asp:Label> <%-- By default the filed will be a label for viewing--%>
                      <%-- The eval() function will binds the title of colums name in the database to the title in browser. So, if changes are made they are reflected --%>
                </ItemTemplate>
                <EditItemTemplate> <%-- when the field is clicked on to be eidted, it will be a textbox so the user can interact with--%>
                    <asp:TextBox ID="txtFarmerID" runat="server" Text='<%# Eval("Farmer_Id") %>'></asp:TextBox>
                     <%-- The eval() function will binds the title of colums name in the database to the title in browser. So, if changes are made they are reflected --%>
                </EditItemTemplate>
                <FooterTemplate><%-- This will be the default area from which new records are added to the table--%>
                    <asp:TextBox ID="txtFarmerIDFooter" runat="server"></asp:TextBox>
                     <%-- A textbox is used for getting the pieces of information to be added to the table--%>
                </FooterTemplate>

            </asp:TemplateField><%-- End of first column--%>

            <%-- COLUMN 2--%>
             <asp:TemplateField HeaderText="First Name">
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtFarmerFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtFarmerFirstNameFooter" runat="server"></asp:TextBox>
                </FooterTemplate>

            </asp:TemplateField>

            <%-- COLUMN 3--%>
             <asp:TemplateField HeaderText="Last Name"> 
                <ItemTemplate>
                    <asp:Label Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtFarmerLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtFarmerLastNameFooter" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>

Below is the C# Code for the Delete Function after you click the delete icon:

 protected void gvFarmer_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        try
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();

                string InsertQuery = "DELETE FROM Farmer WHERE Farmer_Id = @Farmer_Id";
                //parametrized variables are used to prevent sql injection

                SqlCommand insert = new SqlCommand(InsertQuery, con);

                insert.Parameters.AddWithValue("@Farmer_Id", (gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox).Text.Trim());
                //get the info from textbox, trim spaces and store it in appropirate fields in the database

                insert.ExecuteNonQuery(); //function executes the insert query

                PopulateGridView(); //function is called to show updated view.

                lblSuccess.Text = "Record Deleted!";
                lb1Error.Text = "";
            }//using block ends here

        }
        catch (Exception ex)
        {

            lblSuccess.Text = "";
            lb1Error.Text = ex.Message;
        }//end of try catch

    }
4
  • In which line the null exception/NRE occurred? The most suspicious is gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox, which may contain null value. Commented Nov 2, 2018 at 6:47
  • that's the line. Commented Nov 2, 2018 at 6:54
  • then there's your answer Commented Nov 2, 2018 at 6:55
  • I am new to this and don't understand why it is null, is it the way I'm accessing it? I've spent days trying to figure out why Commented Nov 2, 2018 at 6:57

1 Answer 1

1

The most possible cause is this cast:

gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox

This cast will return null value if the row type is not DataRow or the control is not found on respective row and throwing NullReferenceException when using Text property. You should try using Cells property:

insert.Parameters.AddWithValue("@Farmer_Id", (gvFarmer.Rows[e.RowIndex].Cells[n].FindControl("txtFarmerID") as TextBox).Text.Trim());

n indicates the column index where txtFarmerID sets up (usually ID column set as index 0).

If it still doesn't work, add DataKeyNames attribute in the markup:

<asp:GridView ID="gvFarmer" runat="server" DataKeyNames="Farmer_Id" ...>
    <%-- grid contents --%>
</asp:GridView>

Then try using DataKeys collection property:

insert.Parameters.AddWithValue("@Farmer_Id", gvFarmer.DataKeys[e.RowIndex].Value.ToString().Trim());

I think the latter approach is better because you don't need to find out the control which holds unique value to delete the row, since the key field name is already defined.

Similar issue:

GridView Edit and Delete "Object reference" error

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.