Update database from datagridview

2019-09-02 10:35发布

I have googled a lot on updating datagridview to database after editing using the adapter. I referred to several websites that gave me similar examples like the one below. However, I'm getting the "ArgumentNullException was unhandled" error at the first line of my button2_Click.

I am new to programming and I have been taught to declare the adapter as a global, and I did. Why am I still getting null value? Any help would be appreciated. Thank you!

DataTable dt;
DataSet ds;
OleDbDataAdapter objAdapter = new OleDbDataAdapter();

public void button1_Click(object sender, EventArgs e)
{
    //Bind button
    string txt = textBox1.Text;

    string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
    string strSqlStatement = string.Empty;
    strSqlStatement = "SELECT * FROM jiahe WHERE [User] = '" + txt + "'";
    OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
    objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
    DataSet ds = new DataSet();
    dataGridView1.DataSource = ds;
    objAdapter.Fill(ds);

    DataTable dt = ds.Tables[0];
    dataGridView1.DataSource = dt.DefaultView;           

    try
    {
        if (dt.Rows.Count == 1)
        {
            MessageBox.Show("Record found.");
        }
        else
        {
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("Invalid input!");
            }
        }
    }
    catch
    {
        MessageBox.Show("Error!");
    }
}

private void button2_Click(object sender, EventArgs e)
{
    objAdapter.Update(ds);
    dataGridView1.DataSource = ds;
}

2条回答
别忘想泡老子
2楼-- · 2019-09-02 10:51

I encountered the same problem and I fixed it by trying this:

DataSet ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
查看更多
小情绪 Triste *
3楼-- · 2019-09-02 11:00

I think it's simply a confusion between the variables in different scopes. The ds you use in the second button_click is not the same data set you use to populate a grid . Make them the exactly same instance and it will, most likely work.

Edit

to make so should be enough to write instead of

DataSet ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];`

This

ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];`
查看更多
登录 后发表回答