2

Given that I added an item to CheckedListBox this way:

checkedListBox1.Items.Add("ItemA");

And let's say that this is the only item in the control:

string s = checkedListBox1.GetItemText(0);

Now the value of s is "0" when I expect "ItemA". Why can't I get correct value using checkedListBox1.GetItemText(int itemIndex) method?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
ArtK
  • 1,157
  • 5
  • 17
  • 31
  • 2
    Do you mean `CheckedListBox`? – Adam V Sep 14 '16 at 15:58
  • 2
    While Reza's answer is right, I believe you can also use `checkedBoxList1.Items[0].ToString();` to get the text. – Equalsk Sep 14 '16 at 16:02
  • 2
    @Equalsk, you can unless you've set `DisplayMember`, as noted in the [docs](https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.getitemtext(v=vs.110).aspx) – adv12 Sep 14 '16 at 16:04
  • 1
    @Equalsk [`GetItemText`](https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.getitemtext(v=vs.110).aspx) is more suitable, because it also supports `DispayMember` is is set. – Reza Aghaei Sep 14 '16 at 16:04
  • Interesting, I didn't know that. Thanks! :-) – Equalsk Sep 14 '16 at 16:04

2 Answers2

5

You should pass the object which is an item of CheckedListBox to GetItemText:

MessageBox.Show(checkedListBox1.GetItemText(checkedListBox1.Items[0]);

Otherwise GetItemText returns ToString of passed object.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • 1
    This answer is correct, but wow that's a weird API Microsoft provided. Without seeing the method signature and documentation, I would have made the same assumption as the OP. – adv12 Sep 14 '16 at 16:04
  • 1
    @adv12 The thing which is more strange to me is lack of [`GetItemValue`](http://stackoverflow.com/a/38305363/3110834) method in list controls (like `ListBox` or `CheckedListBox`) while IMO it should contain such method like `GetItemText`. – Reza Aghaei Sep 14 '16 at 16:15
  • @adv12 Yeah, the API's kind of odd, not sure if this is an option for the OP, but I usually use `ListView`s https://msdn.microsoft.com/en-us/library/system.windows.forms.listview%28v=vs.110%29.aspx with `CheckBoxes` true instead of a `CheckedListBox`, I find a ListView to be easier to work with in most cases. – jrh Sep 16 '16 at 15:00
  • 1
    @jrh Yes, it could be an option, but `ListView` doesn't support data-binding and doesn't have support for `DisplayMember` and `ValueMember`. I fixed the problem of not having `GetItemValue` [here](http://stackoverflow.com/a/38305363/3110834). – Reza Aghaei Sep 16 '16 at 15:02
2

Use checkedListBox1.Items[0].ToString(); instead of GetItemText()

  • 1
    See [this comment](http://stackoverflow.com/questions/39494797/cant-get-correct-value-from-item-in-checkedboxlist/39494952#comment66307449_39494797). – Reza Aghaei Sep 14 '16 at 16:06