Home »
.Net »
C#.Net »
C#.Net Windows Development
Design a Windows Application to demonstrate the use of ListBox in C#
Here, we are implementing a windows application that will demonstrate example of ListBox in C# with some of the basic operations like Add, Remove, Clear, Get Selected Items etc.
Submitted by IncludeHelp, on September 18, 2018
Following operations are performing on the ListBox:
- Add
- Remove
- Clear
- Get selected items
- etc...
Follow controls are using in the application:
- txtInput (TextBox) : To take user input.
- lblCount (Label) : To show count of list-box items.
- lstItem (ListBox) : List-box to contain list of items.
- btnAdd (Button) : To add entered item into list.
- btnRemove (Button) : To remove selected item from list.
- btnShow (Button) : To show selected item in message-box.
- btnClear (Button) : To clear complete list.
Example (form design):
C# Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyWinApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
lstItem.Items.Add(txtInput.Text);
txtInput.Text = "";
lblCount.Text = "Count: " + lstItem.Items.Count;
}
private void btnRmv_Click(object sender, EventArgs e)
{
lstItem.Items.RemoveAt(lstItem.SelectedIndex);
lblCount.Text = "Count: " + lstItem.Items.Count;
}
private void btnShow_Click(object sender, EventArgs e)
{
MessageBox.Show(lstItem.SelectedItem.ToString());
}
private void btnClr_Click(object sender, EventArgs e)
{
lstItem.Items.Clear();
lblCount.Text = "Count: " + lstItem.Items.Count;
}
private void Form1_Load(object sender, EventArgs e)
{
lblCount.Text = "Count: " + lstItem.Items.Count;
}
}
}
In the above code, we used button click events for performing tasks. We used following methods:
- Listbox.Itmes.Add(text)
- Listbox.Itmes.RemoveAt(index)
- Listbox.Itmes.Clear()
We used some properties like:
- lstItem.Items.Count
- lstItem.SelectedIndex
- lstItem.SelectedItem