0

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?

6
  • what do you mean 'how to set key?' Commented Aug 24, 2017 at 21:39
  • I meant to set key/value for item in ListBox, that after click to get key Commented Aug 24, 2017 at 21:40
  • and what is jobs.get dictionary has not such method Commented Aug 24, 2017 at 21:40
  • stackoverflow.com/a/1507008/669576 Commented Aug 24, 2017 at 21:42
  • 1
    another approach, create a cusotm object that contains key (and maybe value ) and ToString method. Add that object to the listbox Commented Aug 24, 2017 at 21:43

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.