lost_in_the_source
lost_in_the_source

Reputation: 11237

How to use ListBoxes?

I'm a beginner to programming Windows applications in C#, so I do not understand basic controls.

Lets say I am writing a program in which you select a number in a ListBox, and a MessageBox is displayed with that number. How would I associate each item in the list to an event?

Thank you very much. Your help is appreciated.

Upvotes: 0

Views: 1004

Answers (3)

Rohit
Rohit

Reputation: 10296

Assuming it is Winforms,you can access the listbox Selected value changed event.A sample code would be like

     private void listBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        System.Windows.Forms.MessageBox.Show(((System.Windows.Forms.ListBox) (sender)).SelectedItem.ToString());
    }

Upvotes: 0

Nickon
Nickon

Reputation: 10156

To show a message box, you have to set an SelectionChanged event:

listBox.SelectionChanged += (sender, args) => MessageBox.Show(listBox.SelectedItem.ToString());

or simplier for beginner:

listBox.SelectionChanged += ShowMessageBox;

private void ShowMessageBox(object sender, EventArgs e)
{
   MessageBox.Show(listBox.SelectedItem.ToString());
}

Upvotes: 2

user217895
user217895

Reputation: 97

ListBox stores several text items. It can interact with other controls, including Button controls. We use this control in Windows Forms. In the example program it interacts with two Buttons—through the Button Click event handler.

List _items = new List(); // <-- Add this

public Form1()
{
    InitializeComponent();

    _items.Add("One"); // <-- Add these
    _items.Add("Two");
    _items.Add("Three");

    listBox1.DataSource = _items;
}

Upvotes: 0

Related Questions