Listbox items to list C#

This tutorial will discuss the methods of clearing all the contents of a list box 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.

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#.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp GUI

  • Popup Message in C#
  • TextBox New Line in C#
  • report this ad

    List controls:

    In the last article, we had a look at the ItemsControl, which is probably the simplest list in WPF. The ListBox control is the next control in line, which adds a bit more functionality. One of the main differences is the fact that the ListBox control actually deals with selections, allowing the end-user to select one or several items from the list and automatically giving visual feedback for it.

    Here's an example of a very simple ListBox control:

    ListBox Item #1 ListBox Item #2 ListBox Item #3

    This is as simple as it gets: We declare a ListBox control, and inside of it, we declare three ListBoxItem's, each with its own text. However, since the ListBoxItem is actually a ContentControl, we can define custom content for it:

    ListBox Item #1 ListBox Item #2 ListBox Item #3

    For each of the ListBoxItem's we now add a StackPanel, in which we add an Image and a TextBlock. This gives us full control of the content as well as the text rendering, as you can see from the screenshot, where different colors have been used for each of the numbers.

    From the screenshot you might also notice another difference when comparing the ItemsControl to the ListBox: By default, a border is shown around the control, making it look like an actual control instead of just output.

    Data binding the ListBox

    Manually defining items for the ListBox makes for a fine first example, but most of the times, your ListBox controls will be filled with items from a data source using data binding. By default, if you bind a list of items to the ListBox, their ToString[] method will be used to represent each item. This is rarely what you want, but fortunately, we can easily declare a template that will be used to render each item.

    I have re-used the TODO based example from the ItemsControl article, where we build a cool TODO list using a simple Code-behind class and, in this case, a ListBox control for the visual representation. Here's the example:

    using System; using System.Windows; using System.Collections.Generic; namespace WpfTutorialSamples.ListBox_control { public partial class ListBoxDataBindingSample : Window { public ListBoxDataBindingSample[] { InitializeComponent[]; List items = new List[]; items.Add[new TodoItem[] { Title = "Complete this WPF tutorial", Completion = 45 }]; items.Add[new TodoItem[] { Title = "Learn C#", Completion = 80 }]; items.Add[new TodoItem[] { Title = "Wash the car", Completion = 0 }]; lbTodoList.ItemsSource = items; } } public class TodoItem { public string Title { get; set; } public int Completion { get; set; } } }

    All the magic happens in the ItemTemplate that we have defined for the ListBox. In there, we specify that each ListBox item should consist of a Grid, divided into two columns, with a TextBlock showing the title in the first and a ProgressBar showing the completion status in the second column. To get the values out, we use some very simple data binding, which is all explained in the data binding part of this tutorial.

    In the Code-behind file, we have declared a very simple TodoItem class to hold each of our TODO items. In the constructor of the window, we initialize a list, add three TODO items to it and then assign it to the ItemsSource of the ListBox. The combination of the ItemsSource and the ItemTemplate we specified in the XAML part, this is all WPF need to render all of the items as a TODO list.

    Please notice the HorizontalContentAlignment property that I set to Stretch on the ListBox. The default content alignment for a ListBox item is Left, which means that each item only takes up as much horizontal space as it needs. The result? Well, not quite what we want:

    By using the Stretch alignment, each item is stretched to take up the full amount of available space, as you can see from the previous screenshot.

    Working with ListBox selection

    As mentioned, a key difference between the ItemsControl and the ListBox is that the ListBox handles and displays user selection for you. Therefore, a lot of ListBox question revolves around somehow working with the selection. To help with some of these questions, I have created a bigger example, showing you some selection related tricks:

    ListBox selection Show selected Select last Select next Select C# Select all using System; using System.Windows; using System.Collections.Generic; namespace WpfTutorialSamples.ListBox_control { public partial class ListBoxSelectionSample : Window { public ListBoxSelectionSample[] { InitializeComponent[]; List items = new List[]; items.Add[new TodoItem[] { Title = "Complete this WPF tutorial", Completion = 45 }]; items.Add[new TodoItem[] { Title = "Learn C#", Completion = 80 }]; items.Add[new TodoItem[] { Title = "Wash the car", Completion = 0 }]; lbTodoList.ItemsSource = items; } private void lbTodoList_SelectionChanged[object sender, System.Windows.Controls.SelectionChangedEventArgs e] { if[lbTodoList.SelectedItem != null] this.Title = [lbTodoList.SelectedItem as TodoItem].Title; } private void btnShowSelectedItem_Click[object sender, RoutedEventArgs e] { foreach[object o in lbTodoList.SelectedItems] MessageBox.Show[[o as TodoItem].Title]; } private void btnSelectLast_Click[object sender, RoutedEventArgs e] { lbTodoList.SelectedIndex = lbTodoList.Items.Count - 1; } private void btnSelectNext_Click[object sender, RoutedEventArgs e] { int nextIndex = 0; if[[lbTodoList.SelectedIndex >= 0] && [lbTodoList.SelectedIndex < [lbTodoList.Items.Count - 1]]] nextIndex = lbTodoList.SelectedIndex + 1; lbTodoList.SelectedIndex = nextIndex; } private void btnSelectCSharp_Click[object sender, RoutedEventArgs e] { foreach[object o in lbTodoList.Items] { if[[o is TodoItem] && [[o as TodoItem].Title.Contains["C#"]]] { lbTodoList.SelectedItem = o; break; } } } private void btnSelectAll_Click[object sender, RoutedEventArgs e] { foreach[object o in lbTodoList.Items] lbTodoList.SelectedItems.Add[o]; } } public class TodoItem { public string Title { get; set; } public int Completion { get; set; } } }

    As you can see, I have defined a range of buttons to the right of the ListBox, to either get or manipulate the selection. I've also changed the SelectionMode to Extended, to allow for the selection of multiple items. This can be done either programmatically, as I do in the example, or by the end-user, by holding down [Ctrl] or [Shift] while clicking on the items.

    For each of the buttons, I have defined a click handler in the Code-behind. Each action should be pretty self-explanatory and the C# code used is fairly simple, but if you're still in doubt, try running the example on your own machine and test out the various possibilities in the example.

    Summary

    The ListBox control is much like the ItemsControl and several of the same techniques can be used. The ListBox does offer a bit more functionality when compared to the ItemsControl, especially the selection handling. For even more functionality, like column headers, you should have a look at the ListView control, which is given a very thorough description later on in this tutorial with several articles explaining all the functionality.

    This article has been fully translated into the following languages:

    • Chinese
    • Danish
    • French
    • German
    • Italian
    • Polish
    • Portuguese
    • Spanish
    • Vietnamese

    Is your preferred language not on the list? Click here to help us translate this article into your language!

    Video liên quan

    Chủ Đề