Windows Forms combobox - databind to multiple properties
I am having trouble databinding to a Combobox's SelectedValue and Text properties. Here is the relevant code snippet:
DataTable dt1 = DataAccess.GetLoanPurposes();
ddLoanPurpose.DisplayMember = "Name";
ddLoanPurpose.ValueMember = "Value";
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataSource = dt1;
I can bind to either Text or SelectedValue and everything works brilliantly. The trouble comes when I try to bind to both. Only the first Databind开发者_C百科ing works (Text to LoanPurposeString in the example above). If I switch the order of the Databinding...
ddLoanPurpose.DataBindings.Add("SelectedValue", _scenario, "LoanPurpose", false);
ddLoanPurpose.DataBindings.Add("Text", _scenario, "LoanPurposeString", false);
...then I lose the binding of Text to LoanPurposeString but now SelectedValue binds to LoanPurpose. So my question is twofold: Why don't both of the bindings wire up to my _scenario object and why does the order matter?
Databinding to two different properties doesn't seem to be supported (at least not based on my research). In this particular instance, the best solution is to combine the separate properties in my _scenario object (LoanPurpose and LoanPurposeString) into a single KeyValuePair property.
public KeyValuePair<string, string> LoanPurpose { get; set; }
I just need to make sure that the ValueMember variable in the DataSource is a KeyValuePair. So something like...
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Value", typeof(KeyValuePair<string, string>)));
DataRow dRow = dt.NewRow();
dRow["Name"] = "Eric";
dRow["Value"] = new KeyValuePair<string, string>("1", "Eric");
dt.Rows.Add(dRow);
The binding syntax will be the same as in my original question, the only difference is that the ValueMember is now a KeyValuePair object instead of a string.
ddLoanPurpose.DisplayMember = "Name";
ddLoanPurpose.ValueMember = "Value";
ddLoanPurpose.DataSource = dt;
精彩评论