How can I work with the Tag property of a winforms checked listbox item?
-
03-10-2019 - |
Pergunta
How can I write a C# winforms code like this?
CheckedListBox items don't have 'Tag' and 'ValueMember' properties.
I know there are many alternatives to this. But I need to work it this way.
private void LoadPermissionsToCheckedListBox()
{
Role selectedRole = (Role)comboBox1.SelectedItem;
int i = 0;
foreach (Permission p in selectedRole.PermissionItems)
{
checkedListBox1.Items.Add(p);
checkedListBox1.Items[i].Tag = p;
}
checkedListBox1.DisplayMember = "PermissionKey";
checkedListBox1.ValueMember = "PermissionID";
}
Solução
There is no Tag property, but the CheckedListBox accepts any object (you don't have to put just strings in it). You can create your custom class to hold your data:
public class CheckListBoxItem
{
public Permission Tag;
public string Text;
public override string ToString() { return Text; }
}
and then add this object as item
foreach (Permission p in selectedRole.PermissionItems)
{
checkedListBox1.Items.Add(new CheckListBoxItem()
{
Tag = p,
Text = p.PermissionKey
});
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow