Gridview从数据库中删除行

时间:2015-06-24 07:41:27

标签: c# sql gridview

我想通过C#gridview从表中删除记录。问题是这些行只是从gridview中删除而不是从表中删除。我也想从DB中删除它们。这是我的代码。

private void Delete_Click(object sender, EventArgs e)
{
    if (this.dataGridView1.SelectedRows.Count > 0)
    {
        string  a = (string )this.dataGridView1.CurrentCell.Value;
            dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
        DeleteRecord(a);
    }

现在我希望函数DeleteRecord(a)的定义是一个简单的请求,为这个函数提供代码,这个代码显然会有sql查询,这样我就可以通过获取所选行的id来删除表中的行。

1 个答案:

答案 0 :(得分:1)

无法确切地说出答案。 多种方式:让我展示一个。

1)Aspx页面

<asp:GridView DataKeyNames="CategoryID" ID="GridView1" 
       runat="server" AutoGenerateColumns="False" 
       OnRowCommand="GridView1_RowCommand" 
       OnRowDataBound="GridView1_RowDataBound" 
       OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
  <Columns>
   <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
   <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
   <asp:TemplateField HeaderText="Select">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1" 
         CommandArgument='<%# Eval("CategoryID") %>' 
         CommandName="Delete" runat="server">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
  </Columns>
</asp:GridView>

2)添加rowdatabound事件。

protected void GridView1_RowDataBound(object sender, 
                         GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1"); 
    l.Attributes.Add("onclick", "javascript:return " +
    "confirm('Are you sure you want to delete this record " +
    DataBinder.Eval(e.Row.DataItem, "CategoryID") + "')"); 
  }
}

3)最后是RowCommand:

protected void GridView1_RowCommand(object sender, 
                         GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
  {
    // get the categoryID of the clicked row
    int categoryID = Convert.ToInt32(e.CommandArgument);
    // Delete the record 
    DeleteRecordByID(categoryID);
    // Implement this on your own :) 
  }
}