Oct 3 2008

Looping Through Controls In C++ .NET

I ran into a situation where I needed to loop through all TextBox controls in a c++ .net application. I was able to figure out a cheesy way to do it, but it would only get me the controls at the top level. I needed something better, something that would go into all the tab controls, and group boxes and get all those TextBoxes I needed.

I spent about 5 hours today looking all over the place to find the answer. Nobody had one. The only information I could find only have VB .NET code, and even still, nothing that resolved my situation.

Below is the function I came up with. If you want to use this, you will need to use this->Controls and pas that result to the function. If you want to check for other objects, just change the GetType() return value to the control you want.

I tested this by putting text in all the textboxes I had, and I didn’t see any errors at this point.

	private: System::String^ LoopControl(Control^ container,String^ str){
				 for each( Control^ ctl in container->Controls ){
					 if(ctl->GetType()->Name == "TextBox" ){
						 str += "\n" + ctl->Text;
					 }
					 if(ctl->Controls->Count > 0){
						 str = LoopControl(ctl,str);
					 }
				 }
				 return str;
	}

If you want to call this function use this. Just make sure you have a TextBox with a name of textBox5.

        String^ str = "";
	for each(Control^ c in this->Controls){
		 str = LoopControl(c,str);
	 }
	 this->textBox5->Text = str;

LEAVE A COMMENT

Subscribe Form

Subscribe to Blog