Say i have a listbox, and when a single item is selected a corresponding objects properties are shown.

in other words, how would I relate items in a listbox to objects containing data?

Take a look,

....
           public class Item
           {
            public string Text { get; set; }
            public string Value { get; set; }
            public override string ToString()
            {
                return Text;
            }
          }
        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add(new Item() { Text = "A", Value = "1" });
            listBox1.Items.Add(new Item() { Text = "B", Value = "2" });
            listBox1.Items.Add(new Item() { Text = "c", Value = "3" });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Item selIem = (Item) listBox1.SelectedItem;
            if (selIem != null)
                MessageBox.Show(selIem.Text + " " + selIem.Value);
        }

I use adatapost's method a lot. The key is the ToString override.
This is what determines what shows up in the listbox.
I also tend to use the as operator when retrieving the data instead of casting because this does not fail if no selection has been made yet (it returns null).
This is a copy of adatapost's code but using integers instead of strings.

....
           public class RangeItem
           {
            public int Low { get; set; }
            public int High { get; set; }
            public override string ToString()
            {
                return string.Format("{0}...{1}", Low, High);
            }
          }
        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add(new RangeItem() { Low = 1, High = 10 });
            listBox1.Items.Add(new RangeItem() { Low = 100, High = 1000 });
            listBox1.Items.Add(new RangeItem() { Low = 2000, High = 10000 });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RangeItem selIem = listBox1.SelectedItem as RangeItem;
            if (selIem != null)
                MessageBox.Show(selIem.Low.ToString() + " " + selIem.High.ToString() );
        }

Edited 6 Years Ago by nick.crane: n/a

Comments
Hey nick. very well explained:)
This article has been dead for over six months. Start a new discussion instead.