简体   繁体   中英

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!

The Update method of the DataAdapter is used to update the database with the changes made in the 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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