using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _15._7DataGridView直接修改数据
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection getConnection() // 连接数据库
{
string constr = "Server=.;user=sa;pwd=zqyo850619;database=csharpzxw";
SqlConnection mycon = new SqlConnection(constr);
return mycon;
}
private void gdvBind() // 绑定数据
{
SqlConnection mycon = getConnection();
try
{
mycon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select*from mytable001", mycon);
DataTable table = new DataTable();
sda.Fill(table);
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = table;
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
}
catch( Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mycon.Close();
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e) //载入时执行数据绑定方法
{
gdvBind();
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
SqlConnection mycon = getConnection();
try
{
mycon.Open();
string mystr1=dataGridView1.Columns[e.ColumnIndex].HeaderText+"="+"'"+dataGridView1.CurrentCell.Value.ToString()+"'"; //定义获取数据字符串
string mystr2="id="+ dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
string updateSql = "update mytable001 set "+mystr1+" where "+mystr2;
SqlCommand mycmd = new SqlCommand(updateSql, mycon);
mycmd.ExecuteNonQuery();
gdvBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mycon.Close();
}
}
}
}