C#编程-75:DataGridView直接修改数据库
2024-06-25 09:51:41 阅读次数:28
编程开发
- using System;
- using System.Data;
- using System.Windows.Forms;
- using System.Data.SqlClient;
- namespace DataGridViewUpdate
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private SqlConnection GetConnection()
- {
- //string constr = @"Server=(localdb)\Projects;integrated security=SSPI;Initial Catalog=NewDB";
- string constr=@"server=(localdb)\Projects;integrated security=sspi;database=company";
- SqlConnection sqlcon = new SqlConnection(constr);
- return sqlcon;
- }
- private void BindData()
- {
-
- SqlConnection sqlcon = GetConnection();
- try
- {
- sqlcon.Open();
- string sql = "select * from clerk";
- SqlDataAdapter sqladp = new SqlDataAdapter(sql, sqlcon);
- DataTable table = new DataTable();
- sqladp.Fill(table);
- this.dataGridView1.AutoGenerateColumns = true;
- this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
- this.dataGridView1.DataSource = table;
- }
- catch (Exception ex)
- {
-
- MessageBox.Show(ex.Message);
- }
- finally
- {
- sqlcon.Close();
- }
-
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- BindData();
- }
-
- //同步更新数据库
- private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
- {
- SqlConnection sqlcon = GetConnection();
- string str1 = this.dataGridView1.Columns[e.ColumnIndex].HeaderText + "=N'" + this.dataGridView1.CurrentCell.Value.ToString()+"'";
- string str2 = this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
- try
- {
- sqlcon.Open();
- string sql = "update clerk set "+str1+ "where id="+str2;
- SqlCommand sqlcom=new SqlCommand(sql,sqlcon);
- sqlcom.ExecuteNonQuery();
- BindData();
-
- }
- catch (Exception ex)
- {
-
- MessageBox.Show(ex.Message);
- }
- finally
- {
- sqlcon.Close();
- }
- }
- }
- }
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/mouday/3044902,作者:彭世瑜,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:C#编程-147:线程基础
下一篇:JavaFX使用maven-assembly-plugin打包