[英]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.