Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Winforms FindControl?

Back to Forum: Tech Off
  • User profile image
    phreaks

    I am not very experienced with GUI work, but I thought I knew the basics.

    I need to find a textbox of a winform based on the name of the textbox. I thought I could use FindControl, but apparantly there is no FindControl on a Form.

    //Psuedo-code

    Control myTextBox;

    if (htFields.ContainsKey(_field))
    {
       myTextBox = (
    Control) _form.Controls.FindControl  (htFields[_field].ToString());

       myTextBox.Text = _value.ToString();
    }


  • User profile image
    W3bbo

    There's no "FindControl" because it's not needed, simply use the control's identifier.

    If you want to look in the Control collection, well... I've no idea, actually.

  • User profile image
    phreaks

    W3bbo wrote:
    There's no "FindControl" because it's not needed, simply use the control's identifier.

    If you want to look in the Control collection, well... I've no idea, actually.



    That is my problem.
    Currently I have a gigantic switch statement that manually assigns the value of the TextBox using the textboxes hard-coded identifier.

    I am trying to refactor the switch into something more extensible.

    I suppose I could Iterate through all the controls, pull out the Controls of type textBox and then use Reflection to match on the identifier.

    I just thought this type of ability would be supported by the .NET Framework.


  • User profile image
    defstream

    This would work if all controls on the form are unique. Returns the first control found if not. Modified to return null if cannot be found or empty string.  



    [Code]

            private Control FindControl(string strControlName)
            {
                if (strControlName.Length == 0 || this.Controls.Find(strControlName, true).Length == 0)
                    return null;

                return this.Controls.Find(strControlName, true)[0];
            }
    [/Code]

  • User profile image
    phreaks

    defstream wrote:
    This would work if all controls on the form are unique. Returns the first control found if not. Modified to return null if cannot be found or empty string.  



    [Code]

            private Control FindControl(string strControlName)
            {
                if (strControlName.Length == 0 || this.Controls.Find(strControlName, true).Length == 0)
                    return null;

                return this.Controls.Find(strControlName, true)[0];
            }
    [/Code]



    Big Smile

    I had implemented my own FindControl method by recursively walking the control tree, but your implementation is much smaller and much faster.

    Thanks alot, you rule.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.