[英]How Do I Identify DataGrid Row for Deletion?
我目前正在用 C# 重寫我的一個舊的 VB.net 腳本。 我在每一行都有一個 DataGrid 和一個刪除按鈕。 我想將給定的 Id (KeyphraseToBrandId) 傳遞給 OnDeleteCommand,以刪除數據庫中的該行。 我在識別這一行時遇到了麻煩。
這是我的 MyDataGrid_DeleteCommand,它顯示了我嘗試過但沒有奏效的所有內容,作為評論:
protected void MyDataGrid_DeleteCommand(object source, DataGridCommandEventArgs e)
{
String connStr = ConfigurationSettings.AppSettings["ConnectionString"];
// Define db connection
MySqlConnection conn = new MySqlConnection(connStr);
String DeleteSql = "DELETE from KeyphrasesToBrands WHERE KeyphraseToBrandId=?KeyphraseToBrandId";
MySqlCommand DeleteCommand = new MySqlCommand(DeleteSql, conn);
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", MyDataGrid.DataKeys(CInt(E.Item.ItemIndex)));
// This works for Id 8, so it's not the rest of the code
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", "8");
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", MyDataGrid.SelectedDataKey.Value.ToString());
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", MyDataGrid.DataKeys.Equals(e.Item.ItemIndex));
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", e.Item.ItemIndex.ToString());
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", e.Item.ItemIndex);
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", e.CommandArgument.ToString());
// DeleteCommand.Parameters.Add("?KeyphraseToBrandId", e.Item.Cells[0].ToString());
DeleteCommand.Parameters.Add("?KeyphraseToBrandId", e.CommandArgument);
DeleteCommand.Connection.Open();
DeleteCommand.ExecuteNonQuery();
BindGrid();
DeleteCommand.Connection.Close();
}
...這是我的 DataGrid:
<asp:DataGrid ID="MyDataGrid" runat="server" DataKeyField="KeyphraseToBrandId" OnCancelCommand="MyDataGrid_CancelCommand" OnDeleteCommand="MyDataGrid_DeleteCommand" OnSelectedIndexChanged="MyDataGrid_SelectedIndexChanged" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn DataField="KeyphraseText" HeaderText="Keyphrase Text"></asp:BoundColumn>
<asp:BoundColumn DataField="BrandName" HeaderText="Brand Name"></asp:BoundColumn>
<asp:BoundColumn DataField="KeyphraseToBrandId" HeaderText="Keyphrase To Brand Id"></asp:BoundColumn>
<asp:ButtonColumn ButtonType="PushButton" Text="Delete" CommandName="Delete" HeaderText="Delete?" />
</Columns>
</asp:DataGrid>
如何將 KeyphraseBrandId 傳遞給刪除命令,以標識要在數據庫中刪除的這一行?
謝謝
如果要刪除批量選定的行,則可以執行此操作
foreach (DataGridViewRow row in yourDataGridView.SelectedRows)
{
yourDataGridView.Rows.RemoveAt(row.Index);
}
這是查找索引(DataGrid 中列出的行的標識)的工作。 它臨時刪除 Rows,如果您想從數據庫本身中刪除數據,您需要從 Row 獲取身份 ID 並將其刪除或根據您的要求更改活動狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.