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 test1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn;
SqlDataAdapter adapter;
DataSet dataSet = null;
int index1; // 当前行索引
int index2; // 当前列索引
private void Form1_Load(object sender, EventArgs e) //
{
string str = "server = .;database = test; uid = sa; pwd = sa";
conn = new SqlConnection(str);
conn.Open();
string Sqlstr = "select * from Table_1";
adapter = new SqlDataAdapter(Sqlstr, conn);
dataSet = new DataSet();
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
index1 = e.RowIndex;
dataGridView1.Columns["stuNO"].ReadOnly = true;
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
index1 = e.RowIndex;
index2 = e.ColumnIndex;
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataTable dt = dataSet.Tables[0];
adapter.FillSchema(dt, SchemaType.Mapped);
DataRow dr = dt.Rows.Find(dt.Rows[index1]["stuNO"]);
dr[dataGridView1.Columns[index2].HeaderText] = dataGridView1.Rows[index1].Cells[index2].Value.ToString();
SqlCommandBuilder sqlcmd = new SqlCommandBuilder(adapter);
adapter.Update(dt);
MessageBox.Show("数据更新成功!");
}
}
}
在 DataGridView 控件中修改数据
最新推荐文章于 2020-04-08 21:12:40 发布