Passing two different types of controls to a method

R

Robert Bravery

Hi ALl,

I want to create a a generic method to add list items.

At different parts of the app, I will pass it either a listbox control or a
dropdownlist control
then the method will have generic code to add new list items
No I have a lot of loops in adding theses list items, so I don;t really want
to duplicate that code
for eg.

if (comp.IndividualShareholderCollection != null)
{

foreach (IndividualShareholder share in
comp.IndividualShareholderCollection)
{
List.Items.Add(share.ShareholderName);
}
}
if (comp.CompanyShareholderCollection != null)
{
foreach (CompanyShareholder CompShare in
comp.CompanyShareholderCollection)
{
List.Items.Add(CompShare.ShareholderName);
}
}
.....
......
......

Thanks
Robert
 
P

Peter Duniho

Hi ALl,

I want to create a a generic method to add list items.

At different parts of the app, I will pass it either a listbox control
or a dropdownlist control
then the method will have generic code to add new list items
No I have a lot of loops in adding theses list items, so I don;t really
want to duplicate that code
for eg.

It's very difficult to find an actual question in your post. However, if
you are asking how you can write a single block of code that will handle
both a ListBox and a DropDownList control, that should be easy.

First, I'm assuming these are the controls from System.Web.UI.WebControls,
since that's the only place I see a DropDownList. So, given that: both
DropDownList and ListBox inherit ListControl, and it's ListControl that
defines the Items property that you use to add items.

So, just declare your variable as ListControl, and you can assign either a
ListBox or DropDownList to the variable and treat them the same.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top