2014-03-13 38 views
3

我将列表中的项目添加到CheckedListBox。我希望该框可以向用户显示该项目的友好名称,但在用户选择该项目时需要使用“秘密”实际值。在CheckedListBox中显示友好名称

foreach (string s in x) 
{ 
    checkedlistBox1.Items.Add(friendlyValue); 
    //Now how do I get this to have the real value? 
} 

的下拉菜单,我可以设置显示名称和ValueName的东西,并使用类似:

combobox1.Items.Add(new ComboBoxItem { friendlyValue = x, realValue = y }); 

我似乎不能用CheckedListBox做到这一点。

+0

这是WinForms? WPF?网? –

+0

实际上形式。 –

+0

WinForms,对吧?因为在“表单”是指HTML表单。导致一些混淆。 :) –

回答

2

CheckedListBox上设置DisplayMemberValueMember属性。

这些在功能上等同于ComboBoxDisplayNameValueName属性。

public class MyClass 
{ 
    public string FriendlyValue { get; set; } 
    public string RealValue { get; set; } 
} 

public class YourForm : Form 
{ 
    public YourForm() 
    { 
     var friendlyList 
      = new List<string>(); // imagine it's populated with friendly values 

     foreach (var fv in friendlyList) 
     { 
      checkedListBox1.Items.Add(
       new MyClass { FriendlyValue = fv, RealValue = ??? }); 
     } 

     checkedListBox1.DisplayMember = "FriendlyValue"; 
     checkedListBox1.ValueMember = "RealValue";   
    } 
} 
+0

这看起来不可用作为选项。如果我在VisualStudio中键入checkedListBox1.DisplayMember,则不会出现任何结果。它不在列表中。另外,我似乎无法添加任何名为“CheckedListBoxItem”到checkedListBox1.Items.Add。这不是作为命名空间存在的东西。就我2010年的副本而言,没有CheckedListBoxItem这样的事情。 –

+1

@Sephethus由于某种原因,microsoft隐藏了来自intellisense的这些属性。但是当你设置它会工作:) –

+0

我试图设置这两个属性没有智能感知,它没有给我一个错误,所以部分工作。将这些值添加到列表框中怎么样?我尝试使用类似的代码,以上我的comboboxitem例子,除了我使用CheckedListBoxItem,它给出了一个错误,说不存在于命名空间。 –