Jandos

Prerequisites:

Windows forms combobox

1) DropDownStyle = DropDown (allows typing in)

2) AutoCompleteMode = SuggestAppend

3) Populated from a DataTable directly in code. ValueMember = "ID" which is int type, and DisplayMember = "Name" which is string type.

4) SelectedValue is bound to an int (or can be Nullable<int>) type property of a business object, through a BindingSource object.

Required:

Pass null to the property of the business object if the user input doesn't match any value in the list of the combobox. In case, business object's property is int type (not Nullable<int>), business object should throw an error.

The Problem:

The combobox or the BindingSource object doesn't try to pass null to the property of the business object, if a selection or entry doesn't match any value in the list of the combobox, even though it sets its SelectedValue to null.

What might be wrong




Re: Windows Forms Data Controls and Databinding Binding ComboBox to business object issue

Rong-Chun Zhang - MSFT

Hi Jandos,

We need to handle the ComboBox.Validated event and invoke the Binding.WriteValue method in this handler. See my sample below.

Code Snippet

namespace CBO

{

public partial class BindingSelectValue : Form

{

public BindingSelectValue()

{

InitializeComponent();

}

DataTable dt = new DataTable();

cust o = new cust(2, "addfs");

private void BindingSelectValue_Load(object sender, EventArgs e)

{

dt.Columns.Add("aa", typeof(int));

dt.Columns.Add("bb");

for (int i = 0; i < 10; i++)

{

dt.Rows.Add(i, "name" + i);

}

this.comboBox1.DisplayMember = "bb";

this.comboBox1.ValueMember = "aa";

this.comboBox1.DataSource = dt;

this.comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;

this.comboBox1.Validated += new EventHandler(comboBox1_Validated);

this.comboBox1.DataBindings.Add("SelectedValue", o, "Id", true);

}

void comboBox1_Validated(object sender, EventArgs e)

{

this.comboBox1.DataBindings[0].WriteValue();

}

private void button1_Click(object sender, EventArgs e)

{

if (this.comboBox1.SelectedValue == null)

MessageBox.Show("null");

}

private void button2_Click(object sender, EventArgs e)

{

MessageBox.Show(o.Id.ToString());

}

}

class cust

{

public cust(Nullable<int> id, string name)

{

this.id = id;

this.name = name;

}

Nullable<int> id;

public Nullable<int> Id

{

get { return id; }

set { id = value; }

}

string name;

public string Name

{

get { return name; }

set { name = value; }

}

}

}

Hope this helps.

Regards