Clear ListBox in C#

  1. Clear ListBox With the ListBox.Items.Clear() Function in C
  2. Clear ListBox With the DataSource = null Approach in C

This tutorial will discuss the methods of clearing all the contents of a list box in C#.

Clear ListBox With the ListBox.Items.Clear() Function in C

The ListBox.Items.Clear() function clears all the items inside a list box in C#. This function does not return anything, and all the information related to the deleted elements is lost. The following code example shows us how to empty a list box with the ListBox.Items.Clear() function in C#.

private void emptylistbox(object sender, EventArgs e)
{
    listbox1.Items.Clear();
}

In the above code, we emptied the list box listbox1 with the listbox1.Items.Clear() function in C#. Although this approach is good and works just fine with the simple list box. But if our list box is bound to a data source, this approach will not work and show an error. This error can be easily fixed, as shown in the next section.

Clear ListBox With the DataSource = null Approach in C

If our list box is bound to a data source, we can assign a null value to the data source to empty our list box. But this is not a very good approach because we might need to use the same data source later in our code. The best solution for this would be to specify the ListBox.DataSource property equal to null to remove the data source and then use the ListBox.Items.Clear() function to clear the previous items in the list box. The following code example shows us how we can empty a list box with the ListBox.DataSource property in C#.

private void emptylistbox(object sender, EventArgs e)
{
    listbox1.DataSource = null;
    listbox1.Items.Clear();
}

In the above code, we emptied the list box listbox1 with the the listbox1.DataSource = null and listbox1.Items.Clear() function in C#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp GUI

  • Close Form in C#
  • Clear TextBox in C#