首页 新闻 赞助 找找看

为啥下面的代码不能实现对dataGridView中的数据的修改和保存?

0
[待解决问题]

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();
        }
    }
}

Xchao2017的主页 Xchao2017 | 菜鸟二级 | 园豆:202
提问于:2017-07-20 00:02
< >
分享
所有回答(1)
0

其实直接

 dataGridView1.DataSource = ds.Tables[0];

ds.Tables[0].savechanges()就行吧

猝不及防 | 园豆:2731 (老鸟四级) | 2017-07-20 08:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册