我的WPF应用程序使用本地SQLite数据库。我使用此数据库填充数据网格。没关系。但是,我希望用户能够在数据网格中进行更改,然后再更新SQLite数据库。
我尝试了许多方法,整个周末都在互联网上搜索解决方案,但无济于事。抱歉,但是我是WPF的新手,所以这可能非常基础。
这是我的代码:
//Update the SQLite db
private void Button_Click_3(object sender, RoutedEventArgs e)
{
string ConnectionStringDestination = @"Data Source=C:\Test\Testdb.db;Version=3;";
var con = new SQLiteConnection("Data Source=C:\\Test\Testdb.db;Version=3;");
SQLiteConnection cons = new SQLiteConnection(ConnectionStringDestination, true);
try
{
cons.Open();
SQLiteCommand cmd = cons.CreateCommand();
cmd.CommandText = "SELECT RecordId, BatchNumber FROM BatchNumbers";
using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(cmd.CommandText, con))
{
DataTable BatchNumbers = new DataTable();
dataAdapter.Fill(BatchNumbers);
SQLiteCommandBuilder mybuilder = new SQLiteCommandBuilder(dataAdapter);
dataAdapter.UpdateCommand = mybuilder.GetUpdateCommand();
dataAdapter.Update(BatchNumbers);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
我希望数据库更新。但事实并非如此!
这是我尝试过的另一条尝试,但这也不起作用
private void Mydatagrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
string ConnectionStringDestination = @"Data Source=C:\Test\Testdb.db;Version=3;";
var con = new SQLiteConnection("Data Source=C:\\Test\\Testdb.db;Version=3;");
SQLiteConnection cons = new SQLiteConnection(ConnectionStringDestination, true);
SQLiteCommand myCmd = new SQLiteCommand("Select RecordId, BatchNumber FROM BatchNumbers", cons);
SQLiteDataAdapter sda = new SQLiteDataAdapter(myCmd);
DataTable dt = new DataTable("BatchNumbers");
cons.Open();
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
sda.UpdateCommand = builder.GetUpdateCommand();
sda.Update(dt);
cons.Close();
}