我想在窗體中編輯我的datagridview並單擊更新到數據庫的「保存」按鈕。NullReferenceException從datagridview更新數據庫時
public void button1_Click(object sender, EventArgs e)
{
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);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;
try
{
if (dt.Rows.Count == 1)
{
string strLine = string.Empty;
string strUser = string.Empty;
foreach (DataRow dr in dt.Rows)
{
string strTags = dr["Tag ID"].ToString();
strUser = dr["User"].ToString();
string strAge = dr["Age"].ToString();
string strPhoneNumber = dr["Phone Number"].ToString();
DataTable dataTable = new DataTable();
string updateString = @"update jiahe set Age = ' " + strAge + " ' where [User] = '" + textBox1.Text + "'";
OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
cmd1.Connection.Open();
string str = cmd1.ExecuteNonQuery().ToString();
cmd1.Connection.Close();
}
}
else
{
if (dt.Rows.Count == 0)
{
MessageBox.Show("Invalid input!");
}
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
我的 「保存」 按鈕:
private void button2_Click(object sender, EventArgs e)
{
try
{
objAdapter.Update(dt);
}
catch (Exception exx)
{
MessageBox.Show(exx.ToString());
}
}
當我點擊保存,我在objAdapter.Update(DT)的 「對象未設置。」 的錯誤;。請告訴我我在這裏錯過了什麼。我是自學C#,而且還是很新的,所以不要苛刻我。
可能重複(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) –
這裏有一個提示:我敢打賭它不是一樣的'objAdapter'。一個是類成員,另一個是局部變量。 –