Anyone knows how to do this?
I tried this, but it just populates this ComboBox which I already do.
What I need is a way to get the combobox updated whenever the enum property on my object changes:
DataObject.DataEnum
but also get the above Enum updated whenever I change the selected item in the combobox.
Is it possible to do this?
Normally I am used to do the binding this way:
this.TextBox.DataBindings.Add ( "Text", this.DataObject, "Name", false, DataSourceUpdateMode.OnPropertyChanged );
which works great.
You can use a two-way binding on the SelectedItem property of the ComboBox. When adding values to the combo box, be sure to add the enum values and not just strings that match their display name.
comboBox.Items.Add(ConsoleColor.Red);
comboBox.Items.Add(ConsoleColor.Blue);
// ... etc
Now SelectedItem can be set or get as the enum instead of as a string.
EDIT
It sounds like maybe your object doesn't raise property change notifications which Windows Forms requires to detect that changes to the underlying object need to be refreshed in the UI. Here is an article about how to do that.
EDIT 2
Here's a code sample. I verified this works correctly.
public partial class Form1 : Form {
private Person p = new Person( );
public Form1( ) {
InitializeComponent( );
comboBox1.DataSource = Enum.GetValues( typeof( Gender ) );
textBox1.DataBindings.Add( "Text", p, "Name", false, DataSourceUpdateMode.OnPropertyChanged );
comboBox1.DataBindings.Add( "SelectedItem", p, "Gender", false, DataSourceUpdateMode.OnPropertyChanged );
label1.DataBindings.Add( "Text", p, "Name", false, DataSourceUpdateMode.Never );
label2.DataBindings.Add( "Text", p, "Gender", false, DataSourceUpdateMode.Never );
}
private void Form1_Load( object sender, EventArgs e ) {
// yeah, that's right i voted for him,
// go ahead and downvote me
p.Name = "John McCain";
p.Gender = Gender.Male;
}
private void Form1_Click( object sender, EventArgs e ) {
p.Name = "Sarah Palin";
p.Gender = Gender.Female;
}
}
public enum Gender {
Male,
Female
}
public class Person : INotifyPropertyChanged {
private string name;
private Gender gender;
public string Name
{
get { return name; }
set {
name = value;
PropertyChanged( this, new PropertyChangedEventArgs( "Name" ) );
}
}
public Gender Gender {
get { return gender; }
set {
gender = value;
PropertyChanged( this, new PropertyChangedEventArgs( "Gender" ) );
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate {};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With