samedi 10 janvier 2015

C# calling the same function with ListBox or ComboBox

I have series of listboxes and comboboxes that I want to update, so that the items listed are the same as those listed in a IEnumerable<string>. I do understand that data binding might help, but I think it could be a bit of a struggle now, and I'd rather avoid it. I wrote something like this:



public static void UpdateListboxWithStrings(
ListControl listcontrol,
IEnumerable<string> stringlist)
{
Object listcontrolitems;
if (listcontrol is ListBox)
{
listcontrolitems =
((ListBox)listcontrol).Items;
}
else if (listcontrol is ComboBox)
{
listcontrolitems =
((ComboBox)listcontrol).Items;
}
else
{
//// Wrong control type.
//// EARLY EXIT
return;
}
int itemscount = listcontrolitems.Count;
/// More code here...
}


... And troubles begin. Depending on what I add / remove, listcontrolitems appears undefined, or must be initialized, or it doesn't have properties such as Count.


How do you write a function that works with a combobox or in a listbox without code duplication?


Aucun commentaire:

Enregistrer un commentaire