我有一個DataGridView控件和一個保存按鈕。點擊保存按鈕後,我想通過DataAdapter Update()命令將對DataGridView所做的任何更改反映到我的數據庫中。但是,點擊保存按鈕並重新加載表單後,更新不在那裏。對DataGridView的更改沒有反映在數據庫中
這裏是目前保存按鈕全部代碼:
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
con.Open();
SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
myBuilder.GetUpdateCommand();
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
con.Close();
}
編輯:我忘了我的DGV的數據源設置爲數據表。這裏的工作代碼:
private void btnSave_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
dgvProductInfo.DataSource = dt;
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
dt.Clear();
adapter.Fill(dt);
}
}
感謝您的幫助。我正在使用Winforms和DataGridView,因此我相應地調整了我的標籤。我也實現了一個'using'語句。但是,爲了初始化DataAdapter,您需要指定一個'SELECT'命令。 –