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;
}
I encountered the same problem and I fixed it by trying this:
I think it's simply a confusion between the variables in different scopes. The
ds
you use in the secondbutton_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
This