POV
POV

Reputation: 12005

How to add data in ListBox?

I have Dictionary:

 public Dictionary<int, string> jobs = new Dictionary<int, string>();

It is filled like this:

 this.jobs.Add(1, "Усі види підземних робіт, відкриті гірничі роботи.");

I tried to add values from jobs Dictionary:

foreach (KeyValuePair<int, string> kvp in jobs.get()) {
   listBox1.Items.Add(String.Format("№{0} - ({1})", kvp.Key, kvp.Value.ToString()));
}

As you can see I add to list value "№{0} - ({1})". But how to set key?

Upvotes: 0

Views: 700

Answers (1)

ashin
ashin

Reputation: 2603

Here's a sample of what pm100 has suggested:

Create a model class for binding the list box as follows:

class Job
  {
        public int Key { get; set; }

        public string Description { get; set; }

        public override string ToString()
        {
            return String.Format("№{0} - ({1})", this.Key, this.Description);
        }
  }

Next, project a list of Job from the dictionary as follows:

var jobList = this.jobs
                  .Select(it =>
                                new Job
                                {
                                    Key = it.Key,
                                    Description = it.Value
                                })
                  .ToList();

Instead of adding the dictionary items in a for-each loop, bind the data source of the ListBox as follows:

this.listBox1.DataSource = jobList;

And that's about it. The listbox will display each item by invoking the ToString() method overridden in the Job class.

Now you could access the job object and its key by casting the SelectedItem / SelectedItems as follows:

var job = this.listBox1.SelectedItem as Job;
// job.Key

Upvotes: 1

Related Questions