我已将SQL数据库连接到Visual Studio中的C#项目。在一个comboBox中,我从数据库中获取表的名称,当我单击一个按钮时,它会向我显示DataGridView中当前表的内容。我想知道如何从选定的行中保存/删除日期?
Ps:表格有不同的名称和不同的列,我需要一些保存/删除按钮才能适用于所有
答案 0 :(得分:1)
您可以向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)
}
}