Monday, January 18, 2010

VB.NET Looping through user controls on a page?

I have a user control that's added to my page. Inside that user control is a checkbox and on the main page I have a button. When I click that button I need to know which of the checkboxes are checked.





How do I loop through the user controls on a page?VB.NET Looping through user controls on a page?
First of all, you should go over to forums.asp.net. You'll get better help there for .NET related code.


Second of all, I am a C# developer, so I will do my best to write the VB code.





I'm not sure I fully understand your situation. You may want to reword your question more clearly. But I can see two possible scenarios you might be encountering.





Scenario A:


You have multiple instances of the same UserControl on your page and you need to (from the Page) get a list of the CheckBox controls inside these UserControls that are checked?





Scenario B:


You have a single instance of the UserControl on your page and you need to get a list of the CheckBox controls inside it that are checked.





Let me start off by saying, this isn't a very good design. You may want to rethink this to make it work better. A UserControl is a way of encapsulating controls (and their related logic). You should never try to access the controls inside it from an outside class. That kind of breaks the fundamental princible of OOP. However, what you could do is create a public property on your UserControl that would return the selected checkboxes as a List%26lt;CheckBox%26gt; or something.





In C# this would be:


private List%26lt;ListItem%26gt; _SelectedCheckBoxes;


public List%26lt; ListItem %26gt; SelectedCheckBoxes {


get


{


if (_SelectedCheckBoxes == null) {


_SelectedCheckBoxes = new List%26lt;ListItem%26gt;();


foreach (ListItem item in theCheckBoxList.Items) {


if (item.Selected) {


_SelectedCheckBoxes.Add(item);


}


}


}


return _SelectedCheckBoxes;


}








From your Page you would then have a myUserControl.SelectedCheckBoxes property.





Hope some of that helps.VB.NET Looping through user controls on a page?
You do know that you can reference the checkbox directly from the form, right?


Assuming that the GenerateMember property of the checkbox is set to true, you can just do:





If control.CheckBox1.Checked Then ...





But if you really want to loop through all the controls on the user control:





For Each c As Control In control.Controls


聽聽If TypeOf c Is CheckBox Then


聽聽聽聽If CType(c, CheckBox).Checked Then


聽聽聽聽聽聽MsgBox(c.Text)


聽聽聽聽End If


聽聽End If


Next
  • topical cream
  • No comments:

    Post a Comment