qwr qwr
qwr qwr

Reputation: 1059

How to refresh a listbox in C#?

I have done some search in Google but not able to find a useful method...Please help... So I have a listBox that display the data from database, my function allows the user to delete one/multiple data at a time, and of course i would like to refresh my listBox accordingly. I try for example, checkedListBox1.Refresh(); but didn't work. Please help me.

  private void button1_Click(object sender, EventArgs e)
        {

            string item_name = "";
            foreach (object itemChecked in checkedListBox1.CheckedItems)
            {
                item_name = itemChecked.ToString();
                removefromdatabse2(item_name); // a function that update the database
                MessageBox.Show("successfully deleted");
               // checkedListBox1.Refresh();  , which didn't work

            }
        }

Upvotes: 2

Views: 2712

Answers (3)

user1388634
user1388634

Reputation: 1

Clear it and then rebind the listbox to the datasource

Upvotes: 0

Jason Larke
Jason Larke

Reputation: 5599

You can either clear the whole listbox of its items and repopulate it from the database, or locate the item you're removing and remove it manually. Alternatively, using the "DataSource" property on the ListBox control and update the source whenever you run the query.

Upvotes: 2

Bernard
Bernard

Reputation: 7961

You have two options:

  • Delete the selected ListBoxItem instances from the ListBox (using the ListBox.SelectedItems property to get the selected items) and the corresponding items stored in the database. Each ListBoxItem instance should have a unique identifier that matches one used in the database table storing the items.
  • Delete the items stored in the database that correspond to the selected items in the ListBox, clear the ListBox and reload it with the items stored in the database.

Upvotes: 0

Related Questions