Search code examples
c#asp.netinterfacecasting

Checking for the control type


I am able to get the IDs of all the controls of a page and also their type, in the page when i print it it shows

myPhoneExtTxt Type:System.Web.UI.HtmlControls.HtmlInputText

this is generated based on this code

    foreach (Control c in page)
    {
        if (c.ID != null)
        {
            controlList.Add(c.ID +" Type:"+ c.GetType());
        }
    }

But now i need to check its type and access the text in it if its of type HtmlInput and i am not quite sure how to do that.

Like

if(c.GetType() == (some htmlInput))
{
   some htmlInput.Text = "This should be the new text";
}

how can i do this, i think you get the idea?.


Solution

  • This should be all you need if I get what you're asking:

    if (c is TextBox)
    {
      ((TextBox)c).Text = "This should be the new text";
    }
    

    If your primary goal is to just set some text:

    if (c is ITextControl)
    {
       ((ITextControl)c).Text = "This should be the new text";
    }
    

    In order to support a hidden field as well:

    string someTextToSet = "this should be the new text";
    if (c is ITextControl)
    {
       ((ITextControl)c).Text = someTextToSet;
    }
    else if (c is HtmlInputControl)
    {
       ((HtmlInputControl)c).Value = someTextToSet;
    }
    else if (c is HiddenField)
    {
       ((HiddenField)c).Value = someTextToSet;
    }
    

    Additional controls/interfaces would have to be added to the logic.