Jump to content

listBox items with associated string

- - - - -

  • Please log in to reply
3 replies to this topic

#1
DoktorD1313

DoktorD1313

    Newbie

  • Members
  • PipPip
  • 24 posts
Hey guys,

Google is an awesome allie until you can't figure out how to word what youre looking for... haha.. So I appologize in advance if this is a simple question.

I need to populate a listBox with items that have a string associated with them.

In other words, I have an array with two columns. One being a description and the other being the respective string associated with that description. (i.e. Column1: "Scott Electrical" Column2: "000032SE").

How can I associate the items in the listBox with their respective strings so that the string can be assigned to a variable for use later in the code?

Like I said, theres probably easy ways to do this or at least tutorials online, but I just can't seem to get much luck with Google due to not knowing how to properly word what I want to do.

#2
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
You should google "hashtable".
I think this is exactly what you are looking for.

#3
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 243 posts
Following is a simple example of how to do this. The form has two controls, the listbox and a label:
using System;

using System.Collections.Generic;

using System.Windows.Forms;


namespace WindowsFormsApplication1 {

    public partial class Form1 : Form {

        public Form1() {

            InitializeComponent();

            List<MyData> myList = new List<MyData>();

            myList.Add(new MyData("Alan", "Alabama"));

            myList.Add(new MyData("Carl", "California"));

            myList.Add(new MyData("Fred", "Florida"));


            listBox1.DataSource = myList;

            listBox1.DisplayMember = "Name";

            listBox1.ValueMember = "State";


            label1.Text = String.Empty;

        }


        private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {

            label1.Text = listBox1.SelectedValue.ToString();

        }


        private class MyData {

            public String Name { get; private set; }

            public String State { get; private set; }


            public MyData(String name, String state) {

                Name = name;

                State = state;

            }

        }

    }

}


#4
DoktorD1313

DoktorD1313

    Newbie

  • Members
  • PipPip
  • 24 posts
Thanks to both of you, exactly what I was looking for!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users