How to add value to checkedListBox items
Asked Answered
P

2

10

Is it possible to add to checkedListBox item also value and title

checkedListBox1.Items.Insert(0,"title");    

How to add also value?

Potbellied answered 30/12, 2015 at 17:37 Comment(0)
S
9
checkedListBox1.Items.Insert(0, new ListBoxItem("text", "value"));
Sopher answered 30/12, 2015 at 17:42 Comment(4)
sorry for question, what is ListItem in this case?Potbellied
I have error The type or namespace name 'ListItem' could not be found (are you missing a using directive or an assembly reference?)Potbellied
try this: ListBoxItem("text", "value") instead of ListItem("text", "value")Sopher
I can't find any "ListBoxItem" class in Winforms, only in WPF...Centrum
A
8

Try setting the DisplayMember and ValueMember properties. Then you can pass an anonymous object like so:

checkedListBox1.DisplayMember = "Text";
checkedListBox1.ValueMember = "Value";
checkedListBox1.Items.Insert(0, new { Text= "text", Value = "value"})

Edit:

To answer your question below, you can create a class for your item like so:

public class MyListBoxItem
{
    public string Text { get; set; }
    public string Value { get; set; }
}

And then add them like this:

checkedListBox1.Items.Insert(0, new MyListBoxItem { Text = "text", Value = "value" });

And then you can get the value like this:

(checkedListBox1.Items[0] as MyListBoxItem).Value
Annecorinne answered 30/12, 2015 at 18:36 Comment(2)
how to get this valueMeber and Display member foreach (object itemChecked in checkedListBox1.CheckedItems) { ???? }Potbellied
P.S: You need to override ToString() method in MyListBoxItem class. CheckListBox will call your ToString() method.Silvia

© 2022 - 2024 — McMap. All rights reserved.