using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
data();
}
int id = 0;
int rowindex = 0;
public void data()
{
string sql = "server=.;database=Test1;user=sa;pwd=123456";//获得连接数据的基本信息
SqlConnection conn = new SqlConnection(sql); //创建数据库连接对象
conn.Open();//打开数据库
string contain = "select * from TestSave"; //获取TestSave表的数据信息
SqlCommand cmd = new SqlCommand(contain,conn); //执行sqlcommand命令,就可以执行sql命令了
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds); //ds=sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
this.dataGridView1.ReadOnly = false;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = false;
id = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
rowindex = e.RowIndex;
}
private void button1_Click(object sender, EventArgs e)
{
string sql = "server=.;database=Test1;user=sa;pwd=123456";
SqlConnection conn = new SqlConnection(sql);
conn.Open();
string sqlcom = string.Format(@"update TestSave set Age='{0}'
where Name='{1}'",id,
dataGridView1.Rows[rowindex].Cells[1].Value);
SqlCommand cmd = new SqlCommand(sqlcom,conn);
cmd.ExecuteNonQuery();
conn.Close();
data();
}
private void button2_Click(object sender, EventArgs e)
{
/* Thread th = new Thread(new ThreadStart(new MethodInvoker(delegate
{
this.Invoke(new MethodInvoker(delegate { this.Close(); }));
//Application.Run(new Form1());
})));
th.Start();*/
this.Close();
}
}
}
其实直接
dataGridView1.DataSource = ds.Tables[0];
ds.Tables[0].savechanges()就行吧