code_junkie

How do I get at the listbox item's “key” in c# winforms app

Nov 14th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. DictionaryEntry de = (DictionaryEntry)listbox.SelectedItem;
  2. string htKey = de.Key.ToString();
  3.  
  4. public Form1()
  5. {
  6. InitializeComponent();
  7.  
  8. this.listBox1.DisplayMember = "Name";
  9. this.listBox1.ValueMember = "ID";
  10.  
  11. this.listBox1.Items.Add(new Test(1, "A"));
  12. this.listBox1.Items.Add(new Test(2, "B"));
  13. this.listBox1.Items.Add(new Test(3, "C"));
  14. this.listBox1.Items.Add(new Test(4, "D"));
  15. this.listBox1.Items.Add(new Test(5, "E"));
  16. }
  17.  
  18. private void OnSelectedIndexChanged(object sender, EventArgs e)
  19. {
  20. if(-1 != this.listBox1.SelectedIndex)
  21. {
  22. Test t = this.listBox1.Items[this.listBox1.SelectedIndex] as Test;
  23. if(null != t)
  24. {
  25. this.textBox1.Text = t.Name;
  26. }
  27. }
  28. }
  29.  
  30. private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
  31. {
  32. if (ListBox1.SelectedIndex != -1)
  33. {
  34. string orbit = ListBox1.SelectedValue.ToString();
  35. }
  36. }
  37.  
  38. ArrayList planets = new ArrayList();
  39. planets.Add(new Planet("Mercury", "1"));
  40. planets.Add(new Planet("Venus", "2"));
  41.  
  42. //Remember to set the Datasource
  43. ListBox1.DataSource = planets;
  44. //Name and Orbit are properties of the 'Planet' class
  45. ListBox1.DisplayMember = "Name";
  46. ListBox1.ValueMember = "Orbit";
  47.  
  48. KeyValuePair<int, string> kvp = (KeyValuePair<int, string>)listBoxSystems.SelectedItem;
  49. string szValue = kvp.Value;
  50.  
  51. ListBox1.Items[1].toString();//Get value of the #1 Item in the ListBox;
  52.  
  53. String Value;
  54. for(int c=0;c<ListBox1.Items.Count;c++){
  55. Value = Value + ListBox1.Items[c].toString();
  56. }
  57. //Thats it
Add Comment
Please, Sign In to add comment