How to cleanly update database from Datagridview?

Update database from datagridview

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

  • Answer:

    I think it's simply a confussion between the variables in diffeent scopes. The ds you use in second button_click is not the same you use to populate a grid . Make them the exactly same instance and you will, most likely, done. 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];`

Daz at Stack Overflow Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.