C#,添加记录后更新访问数据库

时间:2014-12-27 09:28:32

标签: c#

我正在使用C#visual studio 2012创建应用程序。问题是当我将新记录添加到访问数据库时,我的组合框变得过时(在添加或删除任何值后,值不会改变记录)。关闭问题后,组合框将是最新的,然后再次打开它。那么我怎样才能实现"实时"组合框?

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);
        }

非常感谢

2 个答案:

答案 0 :(得分:0)

您可以为此使用SqlDependency ... https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-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
}

答案 1 :(得分:-1)

您是第一次放入数据,为什么世界上您期望该框自动更新?您将不得不在更改后自行更新,并且没有实际的答案可以确定如果其他人更改数据库需要更新它。