Update database from datagridview

蹲街弑〆低调 提交于 2019-12-12 03:10:08

问题


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

回答1:


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];`



回答2:


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];


来源:https://stackoverflow.com/questions/8653523/update-database-from-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!