[英]Gridview delete row from database
I want to to delete record(s) from table through C# gridview.我想通过 C# gridview 从表中删除记录。 The problem is that the rows are only getting deleted from gridview and not from table.问题是这些行只会从 gridview 中删除,而不是从表中删除。 I want to remove them from DB as well.我也想从数据库中删除它们。 here is my code.这是我的代码。
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);
}
Now I want the definition of function DeleteRecord(a)
its a humble request to give the code for this function which will obviously have the sql query so that i may delete the rows from table by getting the id of selected row.现在我想要函数DeleteRecord(a)
的定义,它是一个谦虚的请求,它提供此函数的代码,该代码显然具有 sql 查询,以便我可以通过获取所选行的 id 从表中删除行。
It is rather impossible to tell the exact answer.要说出确切的答案是相当不可能的。 Multiple ways:Let me show one.多种方式:让我展示一种。
1)Aspx page 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)Add rowdatabound event. 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)And finally RowCommand: 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.