[c#] How to clear all data in a listBox?

I am after a statement that will clear all strings / data that is currently in a listBox, I have tried:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.ResetText();
}

This question is related to c# .net windows listbox

The answer is


If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.

I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"

public List<ExampleItem> ClearExampleItems()
       {
           List<ExampleItem> exampleItems = new List<ExampleItem>();
           exampleItems.Clear();
           return examplelistItems;
        }

ExampleItem is also in a separate class named "ExampleItem.cs"

using System;

namespace        // The namespace is automatically added by Visual Studio
{
    public class ExampleItem
    {
        public int ItemId { get; set; }
        public string ItemType { get; set; }
        public int ItemNumber { get; set; }
        public string ItemDescription { get; set; }

        public string FullExampleItem 
        {
            get
            {
                return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
            }
        }
    }
}

In the code for your Window Form, the following code fragments reference your listbox:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;

namespace        // The namespace is automatically added by Visual Studio
{
    
    public partial class YourFormName : Form
    {
        
        List<ExampleItem> exampleItems = new List<ExampleItem>();

        public YourFormName()
        {
            InitializeComponent();

            // Connect listbox to LIST
            UpdateExampleItemsBinding();
        }

        private void UpdateUpdateItemsBinding()
        {
            ExampleItemsListBox.DataSource = exampleItems;
            ExampleItemsListBox.DisplayMember = "FullExampleItem";
        }

        private void buttonClearListBox_Click(object sender, EventArgs e)
        {
            DataAccess db = new DataAccess();
            exampleItems = db.ClearExampleItems();
            
            UpdateExampleItemsBinding();
        }
    }
}

This solution specifically addresses a Windows Form listbox with the datasource connected to a list.


Try this:

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

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear();
}

If you are using CListBox as pointer (*) use this line: pList1->ResetContent();


Use this:

listBox1.Items.Clear();

If it is bound to a Datasource it will throw an error using ListBox1.Items.Clear();

In that case you will have to clear the Datasource instead. e.g., if it is filled with a Datatable:

  _dt.Clear();   //<-----Here's the Listbox emptied.
  _dt = _dbHelper.dtFillDataTable(_dt, strSQL);

  lbStyles.DataSource = _dt;
  lbStyles.DisplayMember = "YourDisplayMember";
  lbStyles.ValueMember = "YourValueMember";

this should work:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear( );
}

In C# Core DataSource does not exist, but this work fine:

listbox.ItemsSource = null;
listbox.Items.Clear();

This should work:

listBox1.Items.Clear();

Try

private void cleanlistbox(object sender, EventArgs e)
{
   ListBox1.Items.Clear();
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to listbox

Getting value of selected item in list box as string Value does not fall within the expected range Get values from a listbox on a sheet How to create a listbox in HTML without allowing multiple selection? get value from DataTable Get the value for a listbox item by index How to clear all data in a listBox? C# Listbox Item Double Click Event C#: easiest way to populate a ListBox from a List In Python How can I declare a Dynamic Array