步骤:
1.连接数据库
string constr = "server=.;database=tushuguanli;uid=sa;pwd=123456‘‘
SqlConnection con = new SqlConnection(constr);
con.open();
2.使用datagreatview显示数据库数据
SqlDataAdapter sda= new SqlDataAdapter(sql,con);//数据适配器
DataTable dt = new DataTable();//数据表
sda.Fill(dt);//将数据适配器中的数据适配到数据表中
dataGridView1.AutoGenerateColumns=true;//允许自动填充
dataGridView1.DataSource=dt;//将数据表中的数据写入datagridview控件上
3.修改后同步更新数据库
需要使用dataGridView1的CellValueChanged事件,在这个事件下写如下代码
string updateLeMing = dataGridView1.Columns[e.ColumnIndex].HeaderText; //选中单元格的列名
string updatevalue = dataGridView1.CurrentCell.Value.ToString();//当前单元格的值
string updateID = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();//主键的值
string sql = @"update yonghu set "+updateLeMing+"=‘"+updatevalue+"‘ where id="+updateID;
SqlCommand com = new SqlCommand(sql, con);
com.ExecuteNonQuery();
4.修改后的数据重新进行显示;步骤与第二步相同
开始前
修改后
详细代码:
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 TuShuGuanLiXiTong
{
public partial class 信息列表 : Form
{
public 信息列表()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 将数据显示到datagreatview控件中
/// </summary>
private void shujvxianshi()
{
string constr = "server=.;database=tushuguanli;uid=sa;pwd=123456";
SqlConnection con = new SqlConnection(constr);
string sql = "select * from yonghu";
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
sda.Fill(dt);
this.dataGridView1.AutoGenerateColumns = true;//自动填充列
this.dataGridView1.DataSource = dt; //将datatable数据导入到datagridview中
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; //鼠标单机进入修改模式
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
private void 信息列表_Load(object sender, EventArgs e)
{
shujvxianshi();
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
string constr = "server=.;database=tushuguanli;uid=sa;pwd=123456";
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string updateLeMing = dataGridView1.Columns[e.ColumnIndex].HeaderText; //选中单元格的列名
string updatevalue = dataGridView1.CurrentCell.Value.ToString();//当前单元格的值
string updateID = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();//主键的值
string sql = @"update yonghu set "+updateLeMing+"=‘"+updatevalue+"‘ where id="+updateID;
string sql1 = @"update yonghu set leixing=‘管理员‘ where name=‘李四‘";
SqlCommand com = new SqlCommand(sql, con);
com.ExecuteNonQuery();
shujvxianshi();
MessageBox.Show("更新成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}