Frage

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!

War es hilfreich?

Lösung

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);
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top