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";
}
Foi útil?

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
    });
}

Check: http://social.msdn.microsoft.com/Forums/en-us/csharpgeneral/thread/80f29165-acb3-421f-b5bb-856ba99da703

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top