Click to See Complete Forum and Search --> : For each control


Cristiane
July 16th, 2003, 04:36 PM
Hi,

I would like ask your help for the following problem...
I have a fom in asp.net (using vb.net) with some buttons. I want enable/disable this buttons using "For each" statement. I tried the following code in the "Page_Load" but it didn't work...

For each Controls as Button in Me.Controls
If Controls.Text = xxxxxx then
controls.Enabled = True
Else
Controls.Enabled = False
End if
Next

Thanks any help
Cristiane

Mikie
July 17th, 2003, 08:58 AM
Hi!

The most probable reason that you don't find your buttons is that you only look through the first layer of components. What you need to do is to make a recursive method that goes through all controls and all the controls that is contained in the controls. I myself don't know how to write this in VB since I work with C# but this little function will go through all the controls in your form and look for a specific control. You can easily modify this into what you want it to do.

private bool MyFindControl(Control ctrl, string controlId)
{
bool result = false;

//If the control that has been sent to this method is
//the one we are looking for then return the result.

if (ctrl.ID == controlId)
return true;

//If the control that has been sent to this method is
//NOT the one we are looking for, then go through
//all the controls in the control
foreach (Control control in ctrl.Controls)
{
result = MyFindControl(control, controlId);
if (result)
break;
}
return result;
}

In your Page_Load method you call this procedure like this

bool controlFound = MyFindControl(this, "MyControlId");

I hope this will help you out at least to some degree!

Good luck!

//Mikael

Cristiane
July 18th, 2003, 07:26 AM
Hi...

I think you are right so as to I have these 3 controls completely "unknown" to me but, I tried do your suggestion and didn't work too... I go on having only these 3 "ghost controls" :-(
Thanks any help
Cristiane:confused:

Rohit Kukreti
July 18th, 2003, 08:44 AM
Hi

Use the code below

Dim obj As Object
Dim i As Integer
For Each obj In Controls(1).Controls
If TypeOf obj Is Button Then
If obj.GetType().ToString().IndexOf("Button") > 0 Then
'myBut = CType(myControl, Button)
For i = 0 To 1
If obj.Text = "Button" Then
obj.Enabled = True
Else
obj.Enabled = False
End If
Next
End If
End If
Next

hope it helps
--
Rohit