[英]How to bind Enum to ComboBox in a DataGrid
我在Stack Overflow上发现了这个问题,但没有找到答案的地方。
我想将数据网格的ComboBox绑定到返回[Enum Value]之一的property of a class
的property of a class
。
MyEnum
{
[StringValue("SomeVal")]
SomeVal,
[StringValue("AnotherVal")]
AnotherVal,
[StringValue("OneMoreVal")]
OneMoreVal
}
class MyClass
{
public MyEnum A_Value
{
return whatever; // whatever is MyEnum type
}
}
现在,我制作了一个带有组合框的数据网格列,在那里我需要绑定一个属性
myCombo.DataSource = Enum.GetValues(typeof(MyEnum));
myCombo.DataBindings.Add("SelectedValue", myDataSource, bindingPath + ".A_Value");
当我运行此代码时,它失败并显示错误
“无法在没有ValueMember的情况下为组合框设置值”
然后我在下面添加
myCombo.ValueMember = "Value";
这次不会失败,但是没有设置所选值。 有人可以帮我解决这个问题吗?
我指的是:
我假设myDataSource
应该是MyClass
的实现。这是如何对其进行数据绑定的示例。 这有点冗长,但也许有人可以改进它。
public partial class Form2 : Form
{
private MyClass one;
private Label label1;
private ComboBox comboBox1;
private FlowLayoutPanel panel;
private Button btn1;
public Form2()
{
InitializeComponent();
one = new MyClass();
panel = new FlowLayoutPanel();
label1 = new Label();
comboBox1 = new ComboBox();
btn1 = new Button();
btn1.Text = "Click to change Property";
btn1.Click += (sender, args) => { one.A_Value = MyEnum.BtnVal; }; // to test binding to the property
panel.Dock = DockStyle.Fill;
Controls.Add(panel);
panel.Controls.Add(comboBox1);
panel.Controls.Add(label1);
panel.Controls.Add(btn1);
comboBox1.SelectedIndexChanged += (sender, args) =>
{
one.A_Value = (MyEnum)(sender as ComboBox).SelectedItem; // update the object when the ComboBox is changed
};
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
comboBox1.DataBindings.Add("SelectedItem",one,"A_Value"); // update the ComboBox if the Property is changed by something else
label1.DataBindings.Add("Text",one,"A_Value"); // to show that changes happen to the property and not just the ComboBox
}
}
public enum MyEnum
{
[Description("SomeVal")]
SomeVal,
[Description("AnotherVal")]
AnotherVal,
[Description("OneMoreVal")]
OneMoreVal,
[Description("ButtonClickedValue")]
BtnVal
}
public class MyClass : INotifyPropertyChanged
{
private MyEnum whatever;
public MyEnum A_Value
{
get { return whatever; }
set { whatever = value;
PropertyChanged(this, new PropertyChangedEventArgs("A_Value"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
据我了解,您的datagridview
绑定到MyClass
列表。
如果使用DataGridViewComboBoxColumn
类型,则使用属性DatPropertyName
。
'Use property name of your class to where combobox will be binding
myCombo.DataPropertyName = "A_Value"
然后在myCombo.DataSource = Enum.GetValues(typeof(MyEnum));
如果instanceOf MyClass.A_Value
值将在组合框的数据源中,则将显示它。
更新如果您使用常规的ComboBox
控件,则需要指定ValueMember
属性
myCombo.ValueMember = "A_Value";
检查属性名称是否正确。 因为在您的问题上这是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.