[英]Update database from datagridview
使用適配器進行編輯后,我在Google上搜索了很多有關將datagridview更新到數據庫的信息。 我提到了幾個網站,這些網站給了我類似的示例,如下所示。 但是,在button2_Click的第一行出現“ ArgumentNullException未處理”錯誤。
我是編程的新手,我被教過將適配器聲明為全局適配器,我做到了。 為什么我仍然會得到空值? 任何幫助,將不勝感激。 謝謝!
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;
}
我認為這只是不同范圍內變量之間的混淆。 在第二個button_click
使用的ds
與用於填充網格的數據集不同。 將它們設置為完全相同的實例,並且很可能會起作用。
編輯
這樣做應該足以代替
DataSet ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];`
這個
ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];`
我遇到了相同的問題,並嘗試通過以下方法進行了修復:
DataSet ds = new DataSet();
dataGridView1.DataSource = ds;
objAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.