A
Andrus
I need to enter null value from combobox to business object property.
My combobox datasource does not contain ValueMember with null value.
So I tried to create combobox which stores null to bound object when text is
deleted.
However bound object contains old value in this case.
To reproduce:
1. Run code
2. Delete Walter from ComboBox
3. Click button
Observed:
s.CustId contains W
Expected:
s.CustId must be null
How to fix ?
Andrus
using System.Windows.Forms;
using System.Collections.Generic;
class testForm : Form {
Storage s = new Storage();
testForm() {
Customer c = new Customer();
c.Id = "J";
c.Name = "John";
List<Customer> l = new List<Customer>();
l.Add(c);
c = new Customer();
c.Id = "W";
c.Name = "Walter";
l.Add(c);
ComboBox cm = new ComboBox();
cm.DisplayMember = "Name";
cm.ValueMember = "Id";
cm.DataSource = l;
s.CustId = "W";
cm.DataBindings.Add("SelectedValue", s, "CustId");
Controls.Add(cm);
Button b = new Button();
b.Top = 80;
b.Click += new System.EventHandler(b_Click);
Controls.Add(b);
}
void b_Click(object sender, System.EventArgs e) {
if (s.CustId == null)
MessageBox.Show("Empty combobox must store null value");
else
MessageBox.Show(s.CustId.ToString());
}
class Customer {
public string Id { get; set; }
public string Name { get; set; }
}
class Storage {
public string CustId { get; set; }
}
static void Main() {
Application.Run(new testForm());
}
}
My combobox datasource does not contain ValueMember with null value.
So I tried to create combobox which stores null to bound object when text is
deleted.
However bound object contains old value in this case.
To reproduce:
1. Run code
2. Delete Walter from ComboBox
3. Click button
Observed:
s.CustId contains W
Expected:
s.CustId must be null
How to fix ?
Andrus
using System.Windows.Forms;
using System.Collections.Generic;
class testForm : Form {
Storage s = new Storage();
testForm() {
Customer c = new Customer();
c.Id = "J";
c.Name = "John";
List<Customer> l = new List<Customer>();
l.Add(c);
c = new Customer();
c.Id = "W";
c.Name = "Walter";
l.Add(c);
ComboBox cm = new ComboBox();
cm.DisplayMember = "Name";
cm.ValueMember = "Id";
cm.DataSource = l;
s.CustId = "W";
cm.DataBindings.Add("SelectedValue", s, "CustId");
Controls.Add(cm);
Button b = new Button();
b.Top = 80;
b.Click += new System.EventHandler(b_Click);
Controls.Add(b);
}
void b_Click(object sender, System.EventArgs e) {
if (s.CustId == null)
MessageBox.Show("Empty combobox must store null value");
else
MessageBox.Show(s.CustId.ToString());
}
class Customer {
public string Id { get; set; }
public string Name { get; set; }
}
class Storage {
public string CustId { get; set; }
}
static void Main() {
Application.Run(new testForm());
}
}