C#编写一个datagridview获取sql17各字段数据并显示 在datagridview中手动修改各字段的值然后判断是新数据就添加到sql是旧数据就更新sql
以下是使用C#编写的示例代码:
-
首先需要在Windows窗体应用程序中添加一个DataGridView控件,命名为dataGridView1。
-
然后需要在代码中添加以下命名空间:
using System.Data.SqlClient;
- 接下来需要编写连接SQL Server数据库的代码:
string connectionString = "Data Source=(local);Initial Catalog=数据库名称;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString);
- 然后需要编写SQL查询语句并执行查询,将结果显示在DataGridView中:
string queryString = "SELECT * FROM 表名"; SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); dataGridView1.DataSource = dataTable;
- 接下来需要编写DataGridView中数据修改后的事件处理程序:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; string id = row.Cells[0].Value.ToString(); string name = row.Cells[1].Value.ToString(); string age = row.Cells[2].Value.ToString(); string queryString = ""; if (id == "") { //添加新数据 queryString = "INSERT INTO 表名 (name, age) VALUES ('" + name + "', '" + age + "')"; } else { //更新旧数据 queryString = "UPDATE 表名 SET name='" + name + "', age='" + age + "' WHERE id='" + id + "'"; } SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); }
- 最后需要在窗体加载时添加DataGridView的事件处理程序:
private void Form1_Load(object sender, EventArgs e) { dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit); }
以上是一个简单的示例代码,实际应用中还需要处理一些异常情况和数据类型转换等问题
原文地址: https://www.cveoy.top/t/topic/fDep 著作权归作者所有。请勿转载和采集!