user1416156
user1416156

Reputation: 3023

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?.

Upvotes: 25

Views: 77698

Answers (2)

Victor Soho
Victor Soho

Reputation: 1

private Entry GetFocusedTextBox(Layout parent)
{
  
    foreach (var control in parent.Children)
    {
        if(control == null) continue;

        if (control is Entry && (control as Entry).IsFocused )
            return control as Entry;
        else if (control is Layout)
        {
            var result = GetFocusedTextBox((control as Layout)); 
            if (result != null) return result;
        }
    }
    return null;
}

Upvotes: -1

Jaime Torres
Jaime Torres

Reputation: 10515

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.

Upvotes: 57

Related Questions