[英]save changes to database C# ADO.NET
public EmployeeForm()
{
this.bindingSource = new BindingSource();
this.Load += new EventHandler(EmployeeForm_Load);
}
private void EmployeeForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.connection.Close();
this.connection.Dispose();
}
private void RetrieveDataFromTheDatabase()
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"Employee.mdb\"";
this.connection = new OleDbConnection(connectionString);
this.connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "Select * From Employee";
this.adapter = new OleDbDataAdapter();
this.adapter.SelectCommand = command;
this.dataset = new DataSet();
this.adapter.Fill(dataset, "Employee");
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(this.adapter);
commandBuilder.ConflictOption = ConflictOption.OverwriteChanges;
commandBuilder.GetInsertCommand();
commandBuilder.GetDeleteCommand();
commandBuilder.GetUpdateCommand();
}
private void BindControls()
{
this.bindingSource.DataSource = this.dataset.Tables[0];
this.dgvEmployee.DataSource = this.bindingSource;
}
void FileSave_Click(object sender, EventArgs e)
{
this.adapter.Update(this.dataset, "Employee");
this.dgvEmployee.EndEdit();
this.bindingSource.EndEdit();
}
單擊保存按鈕時,我想將所有數據更改保存到數據庫中。 我擁有的代碼不會對數據庫進行更改。 我還想在成功保存后禁用保存按鈕。
您可以讓 visual studio 為您編寫所有這些代碼,包括保存內容:
SELECT * FROM Employee WHERE id = @id
SELECT * FROM Employee WHERE Name LIKE @name
或類似的 - 添加讓您 select 只是某些員工的查詢是個好主意,並進行您想要的搜索在應用程序中執行。 “按名稱搜索”是我認為的合理要求。 當要求為此查詢輸入名稱時,請輸入 FillByName/GetDataByName查看代碼是如何連接的; 這一切都很簡單。 您可以向數據集甚至關系中添加更多表,您可以通過將子節點(不是頂級節點)拖出數據源來顯示相關數據
如果您對構建過程一直覆蓋您的調試數據庫感到厭倦,請在解決方案資源管理器中單擊它,並將復制選項從“始終復制”更改為“如果更新則復制”。 現在只有當您對項目文件夾中的數據庫進行架構更改(添加表等)時,它才會被復制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.