Wrox Home  
Search P2P Archive for: Go

  Return to Index  

aspx thread: Control building - is FindControl ok?


Message #1 by Scott Mitchell <mitchell@4...> on Fri, 10 Aug 2001 11:47:38 -0700
I am working on building compiled Web controls and noticed that there

are two ways to build up composite Web controls.  That is, suppose I

want a textbox and a label in my compiled Web control.  I can do:



	protected override void CreateChildControls()

	{

		Label lblTmp = new Label();

		lblTmp.ID = "lblFoo";

		... set properties

		Controls.Add(lblTmp);



		TextBox txtTmp = new TextBox();

		txtTmp.ID = "txtBar";

		...

		Controls.Add(txtTmp);



		...

	}



and then, at some later point, I can set or read properties of these

controls via:



	((Label) FindControl("lblFoo")).Text = "blah";



Another approach, though, is to create member variables in my class for

each of these controls I'll add:



	Label lblFoo = new Label();

	TextBox txtBar = new TextBox();



	protected override void CreateChildControls()

	{

		lblFoo.ID = "lblFoo";

		... set properties

		Controls.Add(lblFoo);



		txtBar.ID = "txtBar";

		...

		Controls.Add(txtBar);



		...

	}



and then, in other sections, I can reference propeties like:



	txtBar.Text = "blahha!";



So, I guess my question is, "What is a better approach?"  Is there an

expensive hit using FindControl?  Any other reasons for using one

approach over the other?  It seems like the member variable approach

would be best for two reasons: it doesn't use FindControl (I assume that

is a Good Thing), and it seems more readable, for the coder can look and

see what Web controls, exactly, are being created in the composite

compiled Web control by simply reviewing the member variable declaration

section.



Any comments appreciated.  Thanks.



     Scott Mitchell

     mitchell@4...

     http://www.4GuysFromRolla.com/

     http://www.ASPMessageboard.com/

     http://www.ASPFAQs.com/



* When you think ASP, think 4GuysFromRolla.com!






  Return to Index