<summary>
Like a combobox, a list box displays a list of items. Listbox allows you to make either a single selection or multiple selection. Items in a listbox are indexed. The first item is at index 0.
The listbox contains an internal array called Items (same as combobox)
Adding items to and removing items from a listbox is done thru its Items array.
The listbox has a property: Count. It's the number of items in the list.
Use the SelectedIndex to find out the index of the item selected.
The selectedIndex is equal to -1 if no item is selected.
Use the SelectedItem to find out the item selected
</summary>
My Notes:
There are 3 ways to input in listbox.
One is: In [Design mode] click on ... (Property Items)
Write ... anything you want
eg.
Howard
Steve
Karen
etc....
Selection Mode Property give 4 different ways to make selection (None, One, MultiSimple, MultiExtended)
namespace The_List_Box_Control
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//2nd way to input listbox
private void Form1_Load(object sender, EventArgs e)
{
object[] names = {"Sara", "Bill", "Martin", "Susan", "Don"};
listBox1.Items.AddRange(names);
}
private void btnAdd_Click(object sender, EventArgs e)
{
string name = txtName.Text;
if (name != String.Empty)
{
//listBox1.Items.Add(name);
//txtName.Clear(); or
//don't add if it is already in there.
//add it only if it is not contained in the list
if (!listBox1.Items.Contains(name))
{
listBox1.Items.Add(name);
txtName.Clear();
}
}
}
private void btnGetSelection_Click(object sender, EventArgs e)
{
//get the selected index and selected item.
//first check that an item is selected
if (listBox1.SelectedIndex != -1)
{
richTextBox1.Text = "Selected Index: " + listBox1.SelectedIndex + "\n\n" + "Selected Item: " + listBox1.SelectedItem;
}
}
private void btnRemovebyIndex_Click(object sender, EventArgs e)
{
int index = int.Parse(txtIndex.Text);
if (index >= 0 && index < listBox1.Items.Count)
{
listBox1.Items.RemoveAt(index);
}
}
//1. Complete Remove by Item
private void btnRemovebyItem_Click(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
}
}
//2. Add button to remove the Selected Item
private void btnDeleteSelectItem_Click(object sender, EventArgs e)
{
string item = txtItem.Text;
if (item != String.Empty)
{
listBox1.Items.Remove(item);
txtName.Clear();
}
}
//3. All button + Textboxes to insert new name at specified index
private void btnInsert3_Click(object sender, EventArgs e)
{
int index3 = int.Parse(txtIndex3.Text);
if (index3 >= 0)
{
string myname = txtName3.Text;
if (myname != String.Empty)
{
listBox1.Items.Insert(index3, myname);
txtName.Clear();
}
}
}
}
}
//1. Complete Remove by Item
//2. Add button to remove the Selected Item
//3. All button + Textboxes to insert new name at specified index

No comments:
Post a Comment