本实例程序演示了如何在使用DataGridView控件编辑数据后直接将更改保存到数据库中,适用于需要实时更新数据库的应用场景。
在C#程序中实现DataGridView的数据更改后直接保存到数据库的功能可以通过以下代码示例来完成:
```csharp
// 当单元格编辑结束时触发的事件处理方法。
private void dataGridView1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
try
{
// 获取当前行的第一列(假设为ID)的数据值,并将其转换为字符串形式。
string rowid = this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
// 根据单元格的索引获取其对应的数据库字段名,即DataPropertyName属性值。
string cellhead = dataGridView1.Columns[e.ColumnIndex].DataPropertyName;
// 获取当前单元格的数据值,并将其转换为字符串形式。
string cellvalue = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
// 对特定条件进行处理
if (cellhead == domain)
cellhead = [domain];
if (cellvalue == True && cellhead == passed)
cellvalue = 1;
else if(cellhead == passed)
cellvalue = 0;
// 构建SQL更新语句,将修改后的单元格值保存到数据库中。
string sqlcmd = $update domain_info set {cellhead}={cellvalue} where id={rowid};
// 执行数据库命令,并根据结果显示相应的信息给用户
if (dbo.DBcmd(sqlcmd))
resultshow.Text = 编辑成功;
else
resultshow.Text = 编辑失败;
}
catch
{
MessageBox.Show(异常, 错误);
}
}
```
该代码段展示了如何在单元格结束编辑时,获取其值并更新到数据库中。同时对特定的字段和条件进行了特殊处理以确保数据的一致性和准确性。