在 DataGridView 控件中修改数据

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("数据更新成功!");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值