我做了一个修改,你可以看看:
//连接类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;//引入命名空间
namespace WindowsFormsApplication1
{
class Class1
{
//私有的静态的连接字符
private static string constr = "Data Source=.;Initial Catalog=phone;Integrated Security=True";
//声明并初始化connection
public static SqlConnection connection=new SqlConnection(constr);
}
}
//修改更新
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;//引入命名空间
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//声明DataAdapter
private SqlDataAdapter dataAdapter;
//声明并初始化dataSet
DataSet dataSet = new DataSet();
//窗体加载时填充数据
private void Form1_Load(object sender, EventArgs e)
{
//查询用的SQL语句
string sql = "select Id as Id,userName as 姓名,userNum as 编号,userClass as 所属部门 from userInfo"; //初始化DataAdapter
dataAdapter = new SqlDataAdapter(sql, Class1.connection);
//填充DataSet
dataAdapter.Fill(dataSet,"phone");
//指定DataSet数据源
dataGridView1.DataSource = dataSet.Tables["phone"];
}
//单击保存修改按钮时,将数据集的修改提交到数据库
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("确定要将修改的数据保存到数据库吗?","操作提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (result == DialogResult.OK) { //确认保存修改
//自动生成用于修改的Command命令
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
//将数据提交到数据库更新
dataAdapter.Update(dataSet, "phone");
}
}
}
}
界面