使用 ASP GridView 中的删除按钮删除行
Delete Row Using Delete button in ASP GridView
我在 ASP 上有一个 GridView。 NET Web 表单,它显示来自 SQL 数据库中的 table 的一些信息。我还有一些按钮可以删除、更新和添加新数据。但是,我的删除按钮不起作用。我一直收到错误 "Object reference not set to an instance of an object."
我将 post 下面的函数与 table 中的数据。有谁能帮帮我吗?
<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
或在相应行上找不到控件,则此转换将 return 为空值,并且在使用 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());
我认为后一种方法更好,因为您不需要找出具有唯一值的控件来删除行,因为键字段名称已经定义。
类似问题:
我在 ASP 上有一个 GridView。 NET Web 表单,它显示来自 SQL 数据库中的 table 的一些信息。我还有一些按钮可以删除、更新和添加新数据。但是,我的删除按钮不起作用。我一直收到错误 "Object reference not set to an instance of an object."
我将 post 下面的函数与 table 中的数据。有谁能帮帮我吗?
<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
或在相应行上找不到控件,则此转换将 return 为空值,并且在使用 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());
我认为后一种方法更好,因为您不需要找出具有唯一值的控件来删除行,因为键字段名称已经定义。
类似问题: