Dynamically Add UserControl to Panel

  • Thread starter Thread starter Paul
  • Start date Start date
P

Paul

I have a Panel.

Inside of Page_Load, I loop 5 times.

In each loop, I programatically create a usercontrol with LoadControl.

In each loop, I add the UserControl to the Panel.

In each loop, I set the UserControl ID to be unique.

Problem: Only the last UserControl is displayed.

Something like this code:
dim uc as UserControl
dim ind as integer
dim pnl as Panel
For Each DB.DataRow In DB.DataTable.Rows
uc = new UserControl
uc = DirectCast(LoadControl("uc_gv_splits.ascx"), UserControl)
ind = ind + 1
uc.ID = "uc_" & ind
pnl.controls.add(uc)
Next

TIA
 
Did you look at the page source code in your browser to see if the other
controls made it to the browser?
 
It appears that they did. I see divs for the other 4 controls but they are
empty.

One other note:
In my UserControl, I have a function that I need to run. But after I create
the usercontrol programatically with LoadControl, intellisense tells me that
I do not have the capability to run that function (i.e. it doesn't show up in
the intellisense list).

Would you happen to have an explanation for that?

Thanks for your time.
 
In my UserControl, I have a function that I need to run. But after I create
the usercontrol programatically with LoadControl, intellisense tells me that
I do not have the capability to run that function (i.e. it doesn't show up in
the intellisense list).

Would you happen to have an explanation for that?

Two things ...

uc = new UserControl
uc = DirectCast(LoadControl("uc_gv_splits.ascx"), UserControl)

The first line above isn't needed. And the second line can be just:

uc = LoadControl("uc_gv_splits.ascx")

To call a function in that UserControl, you would need to cast the
UserControl to the type containing the function. If the class name
within the UserControl is uc_gv_splits, then you can do:

CType(uc, uc_gv_splits).NameOfFunction()
 
Back
Top