如何使用winforms检查列表框项的Tag属性?

时间:2010-05-20 04:22:06

标签: winforms tags checkedlistbox valuemember

如何编写像这样的C#winforms代码?

CheckedListBox项目没有“Tag”和“ValueMember”属性。

我知道有很多替代方案。但我需要这样做。

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

1 个答案:

答案 0 :(得分:4)

没有Tag属性,但CheckedListBox接受任何对象(您不必只在其中放置字符串)。您可以创建自定义类来保存数据:

public class CheckListBoxItem
{
    public Permission Tag;
    public string Text;
    public override string ToString() { return Text; }
}

然后将此对象添加为项

foreach (Permission p in selectedRole.PermissionItems)
{
    checkedListBox1.Items.Add(new CheckListBoxItem()
    {
        Tag = p,
        Text = p.PermissionKey
    });
}

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