c#-值不能为null.参数名称:dataSource.编辑Datagrid并保存到数据库

您好,我在这里遇到问题.代码看起来像这样.

private void Form3_Load(object sender, EventArgs e)
{ 
     string connectionString =
     "Server=localhost;" +
     "Database=oroderm;" +
     "User ID=root;" +
     "Password=root;" +
     "Pooling=false";
     string query = "Select * from client";
     MySqlConnection conn = new MySqlConnection(connectionString);
     MySqlDataAdapter dAdapter = new MySqlDataAdapter(query, connectionString);
     conn.Open();
     DataSet ds = new DataSet();
     MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(dAdapter);

     dAdapter.Fill(ds, "client");

     BindingSource bSource = new BindingSource();
     bSource.DataSource = ds.Tables["client"];
     dataGridView2.DataSource = bSource;
}

private void button1_Click(object sender, EventArgs e)
{
     DataTable dt = ds.Tables["client"];
     this.dataGridView2.BindingContext[dt].EndCurrentEdit();
     this.da.Update(dt);
}

所以我想要的是,每当我在Datagrid中编辑值时,单击button1(保存按钮)后,它将影响我的数据库.例如如果更改名称后我以罗马人为客户,然后单击button1,则应该更改.但是,我获取值不能为null错误.请有人帮忙. T_T

*编辑:这是更新的代码

private MySqlDataAdapter _da;
        private DataTable _dt;
        private DataSet _ds;

 private void Form3_Load(object sender, EventArgs e)
        {
               updateClient();
        }

public void updateClient()
        {
            string connectionString =
             "Server=localhost;" +
             "Database=oroderm;" +
             "User ID=root;" +
             "Password=root;" +
             "Pooling=false";

            string query = "select * from client";
            MySqlConnection conn = new MySqlConnection(connectionString);
            _da = new MySqlDataAdapter(query, connectionString);
            conn.Open();
            _ds = new DataSet();
            MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(_da);

            _da.Fill(_ds, "client");
            BindingSource bSource = new BindingSource();
            bSource.DataSource = _ds.Tables["client"];
            dataGridView2.DataSource = bSource;
            _da.UpdateCommand = cBuilder.GetUpdateCommand();
        }

private void button1_Click(object sender, EventArgs e)
        {

            _dt = _ds.Tables["client"];
            this.dataGridView2.BindingContext[_dt].EndCurrentEdit();
            this._da.Update(_dt);

        }

解决方法:

我假设您有一个名为ds的实例变量,并且您希望使用Form3_Load方法填充它?那不会发生-因为在Form3_Load中,您已经得到了以下信息:

DataSet ds = new DataSet();

那是在声明一个名为ds的新局部变量,因此,除非您在方法中明确使用this.ds,否则您将不会更改实例变量的值.

我有点惊讶,当您单击按钮时没有收到NullReferenceException,但是也许您有一些代码可以创建一个空的DataSet并在某个地方分配对ds实例变量的引用.无论如何,将上面显示的行更改为:

ds = new DataSet();

应该解决这个问题.

(请牢记,我强烈建议您不要在UI线程中发出数据库请求,并且应该为连接使用using语句,但这是分开的事情.)

上一篇:CodeGo.net>如何更改WPF的DataGrid单元格小部件背景颜色根据单元格的背景颜色?


下一篇:c#-在datagrid中获取行删除事件的隐藏值(ASP Webforms)