【问题标题】:Delete Row Using Delete button in ASP GridView使用 ASP GridView 中的删除按钮删除行
【发布时间】:2019-04-06 09:59:02
【问题描述】:

我在 ASP 上有一个 GridView。 NET Web 表单,它显示 SQL 数据库中表中的一些信息。我还有一些按钮可以删除、更新和添加新数据。但是,我的删除按钮不起作用。我不断收到错误消息“对象引用未设置为对象的实例。”

我将使用表格中的数据发布下面的函数。有人可以帮帮我吗?

 <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>

以下是单击删除图标后删除功能的 C# 代码:

 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

    }

【问题讨论】:

  • 空异常/NRE 发生在哪一行?最可疑的是gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox,其中可能包含空值。
  • 就是这样。
  • 那么这就是你的答案
  • 我是新手,不明白为什么它为空,这是我访问它的方式吗?我花了几天时间试图找出原因

标签: c# asp.net gridview webforms


【解决方案1】:

最可能的原因是这个演员表:

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

如果行类型不是DataRow 或在相应行上找不到控件并在使用Text 属性时抛出NullReferenceException,则此转换将返回空值。您应该尝试使用Cells 属性:

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

n表示txtFarmerID设置的列索引(通常ID列设置为索引0)。

如果还是不行,在标记中添加DataKeyNames属性:

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

然后尝试使用DataKeys集合属性:

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

我认为后一种方法更好,因为您不需要找出具有唯一值的控件来删除行,因为键字段名称已经定义。

类似问题:

GridView Edit and Delete "Object reference" error

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多