Adding ListBox Items
Dynamically
In the previous section, we saw how to add items to a
ListBox at design-time from XAML. We can add items to a ListBox from the
code.
Let's change our UI and add a TextBox and a button control
to the page. The XAML code for the TextBox and Button controls look like this:
<TextBox Height="23"
HorizontalAlignment="Left" Margin="8,14,0,0"
Name="textBox1" VerticalAlignment="Top" Width="127" />
<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top"
HorizontalAlignment="Left" Width="76" Click="button1_Click">
Add Item
</Button>
On button click event handler, we add the content of TextBox
to the ListBox by using the ListBox.Items.Add method. The following code adds
TextBox contents to the ListBox items.
private void
button1_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
On button click event handler, we add the content of TextBox
to the ListBox by using the ListBox.Items.Add method.
Now if you enter text in the TextBox and click Add Item
button, it will add contents of the TextBox to the ListBox.
We can use ListBox.Items.Remove or the
ListBox.Items.RemoveAt method to delete an item from the collection of items in
the ListBox. The RemoveAt method takes the index of the item in the collection.
Now, we modify our application and add a new button called
Delete Item. The XAML code for this button looks like this.
<Button Height="23" Margin="226,14,124,0" Name="DeleteButton"
VerticalAlignment="Top" Click="DeleteButton_Click">
Delete
Item</Button>
The button click event handler looks like following. On this button
click, we find the index of the selected item and call ListBox.Items.RemoveAt
method as following.
private void
DeleteButton_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.RemoveAt
(listBox1.Items.IndexOf(listBox1.SelectedItem));
}