Search code examples
c#.netfindcontrol

using findcontrol to find a control within a literalcontrol


i have a custom control that renders a number of literalcontrols in the createchildcontrols method. as below (there are other lines of literalcontrols being added that i have not uncluded here)

this.Controls.Add(new LiteralControl(string.Format("<input type=\"text\" style=\"display:none\" value=\"{0}\" id=\"{1}\" name=\"{1}\" />", MediaId.ToString(), this.UniqueID)));

i am then trying to validate this textbox via adding the [ValidationProperty("myprop")] at the top of the class. basically i need to validate against the value entered into the textbox. the myprop property is as follows

public string myprop
    {
        get
        {
            Control ctrl = this.FindControl(this.UniqueID);
            string txt = ((TextBox)ctrl).Text;

            try
            {
                MediaId = Convert.ToInt32(txt);
            }
            catch { MediaId = 0; }
            return txt;
        }
    }

unfortunately the findcontrol does not find the textbox at all, i presume because as far as .net is concerned its a literalcontrol, not a textbox at all

now for sure i could change the createchildcontrols to do this

        TextBox tb = new TextBox();
        tb.Text = this.MediaId.ToString();
        tb.ID = this.UniqueID;
        this.Controls.Add(tb);

but because of other limitations of what i am doing i would have to change a great deal more stuff in other places..

is there anyway of getting findcontrol to find the textbox rendered inside the literal, or another method?

thanks

nat


Solution

  • unfortunately the findcontrol does not find the textbox at all, i presume because as far as .net is concerned its a literalcontrol, not a textbox at all

    That is correct. You have to use some other control like a textbox.