c# combobox binding and first null value
I got probably a small problem but can't find workaround...
I have a combobox on a winform, and this combobox has binding to a column in a datatable. This column (keeps printer name) is null value allowed. I want the combobox to display a first value string "default" and then the printers list. But I don't want "default" string to be stored in datatable, just null.
cmbDefaultPrinter.DataSource = this.availablePrinters;
cmbDefaultPrinter.DisplayMember = "Display";
cmbDefaultPrinter.ValueMember = "Value";
cmbDefaultPrinter.DataBindings.Add(new Binding("Text", ctr.ds.Tables[t.toTable], "printer"));
where availablePrinters is a list of this class:
class myPrinters
{
public string Value { get; set; }
public string Display { get; set; }
public myPrinters(string value, string display)
开发者_运维百科 {
this.Value = value;
this.Display = display;
}
}
and first element in availablePrinters is: myPrinter(null, "Default printer");
What am I doing wrong?
Some options:
Given a collection of myPrinter objects, like a List or a bound DataTable, you can simply insert the default value as the first element of the collection. Then, when you DataBind, all the current elements are discarded, and the new ones are reloaded with the blank element on top.
You can also customize the databind by overriding OnDataBound. After all the DataTable's elements are added, go in and manually insert the default value.
You can also forego the default DataBind behavior, and populate the ComboBox yourself. I've done this many times in the case of "lazy-loading" comboboxes (where I first set one item that is the current value for the record, then when they want to drop the list down I go retrieve the values and fully populate the list). It's a little more involved; you need to basically roll your own data binding behavior using Items.Add(). But, it's not that difficult and it gives you more flexibility, including the ability to add items that aren't in the DataSource.
EDIT: In that case (an empty string is written when you want NULL), I would throw the following into an extension method library, and then stick a call to it on the end of comboBox.SelectedValue() when you're retrieving it to stick into your domain object:
public static string NullIfEmpty(this string input)
{
return String.IsNullOrEmpty(input) ? null : input;
}
Basically, web controls convert null to an empty string when setting text, value or other displayed data properties, so they can simplify their internal workings. But, they don't convert back to null, so if you want null instead of an empty string, you have to make the conversion yourself. As the above method shows it's pretty easy.
精彩评论