Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Working with Dynamic Controls

I wanted to find a better way to work with dynamic controls. This is what I was doing before.

Control c = this.wrapper.FindControl("dynamictextbox");

TextBox tb = c as TextBox;

if (tb != null)

{

    Response.Write(tb.Text);

}


as you can see doing this for multiple dynamic controls gets a bit tedious, specially  if you need to access the same control from different methods, so after some refactoring and with the help of generics this is what I came up with.

public T FindControl<T>(Control container, string id) where T : Control

{

    return (container.FindControl(id) as T);

}


pretty simple, takes the id of the control you want to find and the control it's in, casts it to the type you specify and returns. This is how you would use this function:

TextBox tb = FindControl<TextBox>(this.wrapper, "dynamictextbox");


we still haven't solved the issue of using this control within multiple methods, so what we should do is create a property.

private TextBox _dynamicTextBox;

public TextBox DynamicTextBox

{

    get

    {

        if (_dynamicTextBox == null)

        {

            _dynamicTextBox = FindControl<TextBox>(this.wrapper, "dynamictextbox");

        }

        return _dynamicTextBox;

    }

}


Now you can use this like any other control.

Response.Write(this.DynamicTextBox.Text);

No Comments