使用gridview_rowdeleting事件删除行 [英] Delete row using gridview_rowdeleting event
问题描述
我想删除一行在网格视图编程
我创建了这个GridView控件
I'm trying to delete a row in Grid View programmatically
I have created this GridView
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
和我的code的背后是:
and my code behind is:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this data?",
"Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mySqlString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM persons WHERE id = @id", conn);
MySqlParameter param = new MySqlParameter();
try
{
int rowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
cmd.Parameters.AddWithValue("@id", rowID);
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
我收到错误:
指数超出范围。必须是非负和小于集合的大小。
参数名称:索引
I'm getting the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
推荐答案
您格不设置DataKeyNames属性,因此该网格不会跟踪任何datakeys。也许这就是为什么你得到一个索引错误。
Your grid doesn't set the DataKeyNames property, so this grid isn't tracking any datakeys. Probably thats why you are getting an index error.
您应该设置DataKeyNames属性。在您的code,你还需要检查,以确保集合包含elements.The DataKeys集合本身不能为null,但它可以包含零元素。
You should set the DataKeyNames property. In your code you also need to check to make sure the collection contains elements.The datakeys collection itself may not be null, but it can contain zero elements.
这篇关于使用gridview_rowdeleting事件删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!