如何使用新数据刷新列表框?

时间:2017-11-23 13:05:36

标签: c# sql database wpf listbox

我有一个列表框,显示数据库中的所有行。 当我从列表框/数据库编辑一行时,编辑将不会显示在列表框中,直到我重新启动程序。我如何修复,以便在点击“保存更改”按钮后列表框随编辑更新?

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Library;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            var query = "SELECT * FROM Author";
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Author a = new Author();
                        a.Id = reader.GetInt32(0);
                        a.Name = reader.GetString(1);
                        a.Nationality = reader.GetString(2);

                        AuthorListBox.Items.Add(a.Name);

                        Book b = new Book();
                        b.BookId = reader.GetInt32(0);
                        //b.AuthorID = reader.GetInt32(1);
                        b.Title = reader.GetString(2);

                        BookListBox.Items.Add(b.BookId);
                    }
                }
            }
        }
    }

    private void SaveChangesButton_Click(object sender, RoutedEventArgs e)
    {
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Library;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                string query = "UPDATE Author SET AuthorId = '" + this.IdTextBox.Text + "' ," +
                    " Name = '" + this.AuthorNameTextBox.Text + "', Nationality = '" + this.NationalityTextBox.Text +
                    "' WHERE AuthorId = '" + this.IdTextBox.Text + "' ";
                SqlCommand command = new SqlCommand(query, connection);
                command.ExecuteNonQuery();
                MessageBox.Show("Updated the author");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }

        }
    }

3 个答案:

答案 0 :(得分:0)

对我而言,您似乎没有阅读对数据库所做的更改。您只需将Author对象添加到构造函数中的BookListBox.Items集合中。

最简单的方法可能是在添加元素并更新BookListBox.Items集合后再次从数据库中读取所有内容。不要忘记调用refresh()。

答案 1 :(得分:0)

一种方法是将检索数据库值的代码放入一个方法,例如

public void getData(){

}

然后当你更新作者时,在MessageBox.Show之后立即调用这个方法(“更新了作者”);

尝试一下,如果它不起作用可以给你另一个角度。

还将连接字符串放在函数/方法中,以避免在打开数据库连接时重复自己

答案 2 :(得分:0)

MainWindow()的内容提取到另一个函数中。并在SaveChangesButton_Click结束时调用新函数。在刷新内容之前,不要忘记清除列表框。

像这样的东西

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LoadFromDatabase();
    }
    public LoadFromDatabase()
    {

        BookListBox.Items.Clear(); //Without this you'll get an ever expanding list
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Library;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            var query = "SELECT * FROM Author";
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Author a = new Author();
                        a.Id = reader.GetInt32(0);
                        a.Name = reader.GetString(1);
                        a.Nationality = reader.GetString(2);

                        AuthorListBox.Items.Add(a.Name);

                        Book b = new Book();
                        b.BookId = reader.GetInt32(0);
                        //b.AuthorID = reader.GetInt32(1);
                        b.Title = reader.GetString(2);

                        BookListBox.Items.Add(b.BookId);
                     }
                 }
             }
         }
     }

    private void SaveChangesButton_Click(object sender, RoutedEventArgs e)
    {
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Library;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                string query = "UPDATE Author SET AuthorId = '" + this.IdTextBox.Text + "' ," +
                " Name = '" + this.AuthorNameTextBox.Text + "', Nationality = '" + this.NationalityTextBox.Text +
                "' WHERE AuthorId = '" + this.IdTextBox.Text + "' ";
                SqlCommand command = new SqlCommand(query, connection);
                command.ExecuteNonQuery();
                MessageBox.Show("Updated the author");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }

        }
        LoadFromDatabase();
    }
}