繁体   English   中英

Gridview从数据库中删除行

[英]Gridview delete row from database

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

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)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 :) 
  }
}

暂无
暂无

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

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