C# 将枚举绑定到 WinForms 组合框,然后对其进行设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/906899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding an enum to a WinForms combo box, and then setting it
提问by
a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:
很多人已经回答了如何在 WinForms 中将枚举绑定到组合框的问题。就像这样:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
But that is pretty useless without being able to set the actual value to display.
但是,如果无法设置要显示的实际值,那将毫无用处。
I have tried:
我试过了:
comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null
I have also tried:
我也试过:
comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1
Does anyone have any ideas how to do this?
有没有人有任何想法如何做到这一点?
回答by rein
Try:
尝试:
comboBox1.SelectedItem = MyEnum.Something;
EDITS:
编辑:
Whoops, you've tried that already. However, it worked for me when my comboBox was set to be a DropDownList.
哎呀,你已经试过了。但是,当我的组合框设置为 DropDownList 时,它对我有用。
Here is my full code which works for me (with both DropDown and DropDownList):
这是我的完整代码(使用 DropDown 和 DropDownList):
public partial class Form1 : Form
{
public enum BlahEnum
{
Red,
Green,
Blue,
Purple
}
public Form1()
{
InitializeComponent();
comboBox1.DataSource = Enum.GetValues(typeof(BlahEnum));
}
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedItem = BlahEnum.Blue;
}
}
回答by rein
You could use the "FindString.." functions:
您可以使用“FindString..”函数:
Public Class Form1
Public Enum Test
pete
Hyman
fran
bill
End Enum
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = [Enum].GetValues(GetType(Test))
ComboBox1.SelectedIndex = ComboBox1.FindStringExact("Hyman")
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Test.Hyman.ToString())
ComboBox1.SelectedIndex = ComboBox1.FindStringExact([Enum].GetName(GetType(Test), Test.Hyman))
ComboBox1.SelectedItem = Test.bill
End Sub
End Class
回答by bruno conde
comboBox1.SelectedItem = MyEnum.Something;
should work just fine ... How can you tell that SelectedItem
is null?
应该可以正常工作......你怎么知道它SelectedItem
是空的?
回答by Mehmet Aras
You can use a list of KeyValuePair values as the datasource for the combobox. You will need a helper method where you can specify the enum type and it returns IEnumerable> where int is the value of enum and string is the name of the enum value. In your combobox, set, DisplayMember property to 'Key' and ValueMember property to 'Value'. Value and Key are public properties of KeyValuePair structure. Then when you set SelectedItem property to an enum value like you are doing, it should work.
您可以使用 KeyValuePair 值列表作为组合框的数据源。您将需要一个辅助方法,您可以在其中指定枚举类型并返回 IEnumerable>,其中 int 是枚举的值,字符串是枚举值的名称。在您的组合框中,将 DisplayMember 属性设置为“Key”,将 ValueMember 属性设置为“Value”。Value 和 Key 是 KeyValuePair 结构的公共属性。然后,当您将 SelectedItem 属性设置为您正在执行的枚举值时,它应该可以工作。
回答by Mehmet Aras
At the moment I am using the Items property rather than the DataSource, it means I have to call Add for each enum value, but its a small enum, and its temporary code anyway.
目前我正在使用 Items 属性而不是 DataSource,这意味着我必须为每个枚举值调用 Add,但它是一个小枚举,无论如何它都是临时代码。
Then I can just do the Convert.ToInt32 on the value and set it with SelectedIndex.
然后我可以对值执行 Convert.ToInt32 并使用 SelectedIndex 设置它。
Temporary solution, but YAGNI for now.
临时解决方案,但现在是 YAGNI。
Cheers for the ideas, I will probably use them when I do the proper version after getting a round of customer feedback.
为这些想法干杯,在收到一轮客户反馈后,我可能会在我做正确的版本时使用它们。
回答by jmservera
The code
编码
comboBox1.SelectedItem = MyEnum.Something;
is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:
没关系,问题肯定出在DataBinding上。DataBinding 赋值发生在构造函数之后,主要是第一次显示组合框时。尝试在 Load 事件中设置该值。例如,添加以下代码:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
comboBox1.SelectedItem = MyEnum.Something;
}
And check if it works.
并检查它是否有效。
回答by ScottE
I use the following helper method, which you can bind to your list.
我使用以下辅助方法,您可以将其绑定到您的列表。
''' <summary>
''' Returns enumeration as a sortable list.
''' </summary>
''' <param name="t">GetType(some enumeration)</param>
Public Shared Function GetEnumAsList(ByVal t As Type) As SortedList(Of String, Integer)
If Not t.IsEnum Then
Throw New ArgumentException("Type is not an enumeration.")
End If
Dim items As New SortedList(Of String, Integer)
Dim enumValues As Integer() = [Enum].GetValues(t)
Dim enumNames As String() = [Enum].GetNames(t)
For i As Integer = 0 To enumValues.GetUpperBound(0)
items.Add(enumNames(i), enumValues(i))
Next
Return items
End Function
回答by ncoder83
Let's say you have the following enum
假设您有以下枚举
public enum Numbers {Zero = 0, One, Two};
You need to have a struct to map those values to a string:
您需要有一个结构来将这些值映射到一个字符串:
public struct EntityName
{
public Numbers _num;
public string _caption;
public EntityName(Numbers type, string caption)
{
_num = type;
_caption = caption;
}
public Numbers GetNumber()
{
return _num;
}
public override string ToString()
{
return _caption;
}
}
Now return an array of objects with all the enums mapped to a string:
现在返回一个对象数组,其中所有枚举都映射到一个字符串:
public object[] GetNumberNameRange()
{
return new object[]
{
new EntityName(Number.Zero, "Zero is chosen"),
new EntityName(Number.One, "One is chosen"),
new EntityName(Number.Two, "Two is chosen")
};
}
And use the following to populate your combo box:
并使用以下内容填充您的组合框:
ComboBox numberCB = new ComboBox();
numberCB.Items.AddRange(GetNumberNameRange());
Create a function to retrieve the enum type just in case you want to pass it to a function
创建一个函数来检索枚举类型,以防万一您想将其传递给函数
public Numbers GetConversionType()
{
EntityName type = (EntityName)numberComboBox.SelectedItem;
return type.GetNumber();
}
and then you should be ok :)
然后你应该没问题:)
回答by Proteux
public Form1()
{
InitializeComponent();
comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
comboBox.DisplayMember = "Name";
}
public class EnumWithName<T>
{
public string Name { get; set; }
public T Value { get; set; }
public static EnumWithName<T>[] ParseEnum()
{
List<EnumWithName<T>> list = new List<EnumWithName<T>>();
foreach (object o in Enum.GetValues(typeof(T)))
{
list.Add(new EnumWithName<T>
{
Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
Value = (T)o
});
}
return list.ToArray();
}
}
public enum SearchType
{
Value_1,
Value_2
}
回答by Johan
Old question perhaps here but I had the issue and the solution was easy and simple, I found this http://www.c-sharpcorner.com/UploadFile/mahesh/1220/
老问题也许在这里,但我遇到了问题,解决方案很简单,我找到了这个http://www.c-sharpcorner.com/UploadFile/mahesh/1220/
It makes use of the databining and works nicely so check it out.
它利用了数据绑定并且运行良好,所以请检查一下。