Working with ListBox elements in a user control

2019-08-26 02:53发布

问题:

I have a user control (ucMarket) which contains (for the purpose of simplicity) two controls: a ListBox (ucListBox) and a Label (ucLabel). I need to create multiple instances of that user control on the page dynamically (depending on the results from a DataSet), and I add them using a foreach statement and the following:

Panel1.Controls.Add(ucMarket1);

But how do I get access to the ListBox properties like Rows ? The only thing I have found so far is to cast the control as a ListBox:

ListBox listBox1 = (ListBox)ucMarket1.FindControl("ucListBox");
listBox1.Rows = 10;

For the Label part, I guess I can also do something similar:

label1 = (Label)ucMarket1.FindControl("ucLabel");

But then, how do I put that information back into the user control ? Is there a way to work directly with the user control instead of casting ?

回答1:

Ok a couple of things. from a naming convention point of view, don't call the label & listbox, ucSOMETHING. This is very confusing and not clear from your example whether you're referring to the asp:Label control or some custom userControl you've written. As for accessing your controls.

I'm assuming you are creating and adding a bunch of user controls in the following manner.

for(int i = 0; i < 5; i++)
{
   var control = Page.LoadControl("~/Path/To/ucMarket.ascx");
   control.Id = "ucMarket" + i;
   Panel1.Controls.Add(control);
}

So your best bet is to expose the Listbox on your Control as a public property.

public class ucMarket : UserControl
{
   public ListBox TheListBox
   {
       get { return ucListBox; }
   }
}

That way you could access your listbox in the following way.

var ctrl = Panel1.FindControl("ucMarket1") as ucMarket;
ctrl.TheListBox.Rows ;