c# DataGridView插入和删除选定的行
本文关键字:删除 DataGridView 插入 | 更新日期: 2023-09-27 18:04:04
我已经将我的SQL数据库连接到Visual Studio中的c#项目。在comboBox中,我从数据库中获取表的名称,当我单击一个按钮时,它会在DataGridView中显示当前表的内容。我想知道如何从选定的行保存/删除日期?
Ps:表有不同的名称和不同的列,我需要一些保存/删除按钮的工作为所有
你可以给DataGridView添加按钮,并使用CellContentClick事件。这就是添加按钮的方法:
DataGridViewButtonColumn editButton = new DataGridViewButtonColumn();
editButton.HeaderText = "Update";
editButton.Text = "Update";
editButton.UseColumnTextForButtonValue = true;
editButton.Width = 80;
dbgViewObj.Columns.Add(editButton);//dbgViewObj is your datagridview control
DataGridViewButtonColumn deleteButton = new DataGridViewButtonColumn();
deleteButton.HeaderText = "Delete";
deleteButton.Text = "Delete";
deleteButton.UseColumnTextForButtonValue = true;
deleteButton.Width = 80;
dbgViewObj.Columns.Add(deleteButton);
那么你的CellContentClick可以看起来像这样:
private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int check = 0;
int currentRow = e.RowIndex;
if (e.RowIndex == -1 || e.ColumnIndex == -1)
{
return;
}
if (dgv.Columns[e.ColumnIndex].HeaderText == "Delete" && currentRow >= 0)
{
//do your delete stuff (query a delete query)
}
if (dgv.Columns[e.ColumnIndex].HeaderText == "Update" && currentRow >= 0)
{
//do your update stuff (query an update statement)
}
}