C# C、 添加记录后更新access数据库
我正在使用C visual studio 2012创建应用程序。问题是,当我将新记录添加到access数据库中时,我的组合框会过期,并且在添加或删除任何记录后,值不会改变。关闭问题并再次打开后,组合框将是最新的。那么如何制作实时组合框呢C# C、 添加记录后更新access数据库,c#,C#,我正在使用C visual studio 2012创建应用程序。问题是,当我将新记录添加到access数据库中时,我的组合框会过期,并且在添加或删除任何记录后,值不会改变。关闭问题并再次打开后,组合框将是最新的。那么如何制作实时组合框呢 try { connection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select AccountNumber from Account";
//MessageBox.Show(query); for checking
command.CommandText = query;
//ExecuteNonQuery() : use for update,delete or instert into the database
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read()) //return true
{
comboListAcc.Items.Add(reader[0].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
非常感谢你第一次把数据放进去,为什么你希望盒子会自动更新?更改后,您必须自己更新它,如果其他人更改了数据库,则无法确定是否需要更新它。您可以为此使用SqlDependency
显示如何将其绑定到组合框。我编辑帖子并将代码放入其中
using (SqlCommand command=new SqlCommand("select AccountNumber from Account", connection))
{
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency=new SqlDependency(command);
// Subscribe to the SqlDependency event.
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
// Execute the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// As you already have for first update
}
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e )
{
// Clear and re-add
}