繁体   English   中英

在ASP GridView中使用“删除”按钮删除行

[英]Delete Row Using Delete button in ASP GridView

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

    }

最可能的原因是此强制类型转换:

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

如果行类型不是DataRow或在相应的行上找不到控件,则此DataRow类型转换将返回null值,并在使用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在标记中添加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编辑和删除“对象引用”错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM