[Solved] Method that operates in a specific object (textBox)


Well…this question raises plenty of others, but if you’re wanting to check if an object passed into a method is a TextBox, and then to set the Text property of that, you’d need:

private void ChangeText(object target)
{
    var tBox = target as TextBox;

    if (tBox != null)
        tBox.Text = "new value";  
}

EDIT

This is now straying into the area where I’d want to ask why you need this, as what I’m going to suggest may well not be the best answer to the problem, but here we go. If you want to know if an object has a Text property, and to set that value accordingly, you can use this.

On my *.aspx page, I have:

<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:CheckBox runat="server" ID="CheckBox1" />
<asp:RadioButton runat="server" ID="RadioButton1" />
<asp:Panel runat="server" ID="Panel1"></asp:Panel>

My Page_Load event looks like this:

protected void Page_Load(object sender, EventArgs e)
{
    ChangeText(TextBox1);
    ChangeText(RadioButton1);
    ChangeText(CheckBox1);
    ChangeText(Panel1);
}

And the implementation of ChangeText() is as follows:

private void ChangeText(object target)
{
    var textProperty = target.GetType().GetProperty("Text");

    if (textProperty != null)
    {
        try
        {
            target.GetType().GetProperty("Text").SetValue(target, "New Value", null);
        }
        catch (Exception ex)
        {
            if (ex is ArgumentException
                || ex is MethodAccessException
                || ex is TargetInvocationException)
            {
                // Unable to set the property for whatever reason
                return;
            }

            // All other exceptions -- something unexpected happened.
            throw;
        }
    }
}

The first three elements have their Text properties amended; the Panel does not, as there’s no Text property on there.

1

solved Method that operates in a specific object (textBox)