简体   繁体   English

C#数据绑定列表框刷新

[英]C# Databound Listbox Refresh

I've checked the answers on this topic however I still have no idea why this is not working! 我已经检查了有关该主题的答案,但是我仍然不知道为什么这不起作用! PLEASE HELP! 请帮忙!

    private void btnAdd_Click(object sender, EventArgs e)
    {
        SqlCeCommand insTitle = new SqlCeCommand("Insert into Titles(Title) values('" + txtAddTitle.Text +"')");
        insTitle.Connection = dbConnection;

        try 
        {
            if (dbConnection.State == ConnectionState.Closed) { dbConnection.Open(); }
            insTitle.ExecuteNonQuery();


            this.hRDataSet.AcceptChanges();
            this.titlesTableAdapter.Update(this.hRDataSet);
            this.tableAdapterManager.UpdateAll(this.hRDataSet);

            lstTitles.BeginUpdate();
            lstTitles.DataSource = titlesBindingSource;
            lstTitles.DisplayMember = "Title";
            lstTitles.ValueMember = "Title_ID";
            lstTitles.EndUpdate();
        }
        catch (Exception insErr)
        {
            MessageBox.Show(insErr.Message);
        }
    }

The listbox "lstTitles" won't refresh and doesn't show the added items despite the fact that they are in the database! 列表框“ lstTitles”将不会刷新,并且不会显示添加的项目,即使它们已在数据库中!

The Update method of the DataAdapter is used to update the database with the changes made in the DataSet . DataAdapterUpdate方法用于使用DataSet所做的更改来更新数据库。 What you need to do here is the opposite: you need to update the DataSet with the modified data from the database, so you should use Fill , not Update . 你需要在这里做的是相反的:你需要更新DataSet与从数据库中修改的数据,所以你应该使用Fill ,没有Update

Anyway, your approach is not optimal; 无论如何,您的方法不是最佳的。 since you're working with datasets, you should add the new value to the appropriate table in the DataSet , and then update the database with the Update method. 由于要使用数据集,因此应将新值添加到DataSet的适当表中,然后使用Update方法更新数据库。 The ListBox will automatically pick up the changes. 列表框将自动获取更改。

private void btnAdd_Click(object sender, EventArgs e)
{
    try 
    {
        // Add a row to the DataTable
        DataRow row = hRDataSet.Titles.NewRow();
        row["Title"] = txtAddTitle.Text;
        hRDataSet.Titles.Rows.Add(row);

        // Update the database
        this.titlesTableAdapter.Update(this.hRDataSet);

        // That's it, you're done ;)
    }
    catch (Exception insErr)
    {
        MessageBox.Show(insErr.Message);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM