在datagirdview中选中数据后添加到数据库中
时间: 2023-11-15 13:05:07 浏览: 34
首先,你需要在 DataGridView 控件中选中要添加到数据库中的行。然后,你可以通过以下步骤将选定的数据添加到数据库中:
1. 创建一个连接对象,并打开数据库连接。
2. 创建一个 SQL 插入语句,将选定的数据插入到数据库表中。
3. 创建一个命令对象,并将 SQL 插入语句和连接对象传递给它。
4. 使用命令对象的 ExecuteNonQuery 方法执行 SQL 插入语句。
5. 关闭连接对象。
下面是一个示例代码,可以帮助你了解如何将选定的数据添加到数据库中:
```csharp
// 假设你的 DataGridView 控件名为 dataGridView1。
// 假设你的数据库连接字符串为 connectionString。
// 假设你要将选定的数据插入到名为 tableName 的数据库表中。
// 获取选定的行。
var selectedRows = dataGridView1.SelectedRows;
// 创建连接对象。
using (var connection = new SqlConnection(connectionString))
{
// 打开数据库连接。
connection.Open();
// 遍历选定的行。
foreach (DataGridViewRow row in selectedRows)
{
// 创建 SQL 插入语句。
var sql = $"INSERT INTO {tableName} (column1, column2, column3) VALUES (@value1, @value2, @value3)";
// 创建命令对象。
using (var command = new SqlCommand(sql, connection))
{
// 设置参数。
command.Parameters.AddWithValue("@value1", row.Cells[0].Value);
command.Parameters.AddWithValue("@value2", row.Cells[1].Value);
command.Parameters.AddWithValue("@value3", row.Cells[2].Value);
// 执行 SQL 插入语句。
command.ExecuteNonQuery();
}
}
// 关闭数据库连接。
connection.Close();
}
```
请注意,上面的示例代码仅供参考。具体实现可能因你的具体需求而有所不同。