我在Stack Overflow上找到了这个,但没有我能得到答案的地方。
我想将数据网格的ComboBox绑定到property of a class
,返回[Enum Value之一]。
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";
这次没有失败,但没有设置选定的值。 有人可以帮我解决这个问题吗?
我所说的:
答案 0 :(得分:1)
我假设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 { };
}
答案 1 :(得分:0)
据我所知,您的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";
检查物业名称是否正确。因为在你质疑它是错误的。