Functions with Textbox and Buttons type parameters

Asked

Viewed 673 times

4

I have a program that at some point works with the visibility of an object.
I’m creating a function and I don’t know how to reference objects.

private void Visible(object x, object y, object z, object a) 
{    
    x.Visible = true;
    y.Visible = true;
    z.Visible = true;
    a.Visible = true;
}

The .Visible are in red underline, before I was doing manually, but with function decreases the number of lines of code.
How do I make the reference to TextBoxes and Buttons?

  • can you explain better? And improve if possible the part of the code...

  • For example, I want to click on a button it will show +4 buttons .

  • I have several buttons with the same function of changing the visibility of other 4 , so to decrease the amount of codes I need to do the function , within this function I pass the parameters , which in case would be the components , For example " Visibility (textBox1,Button1,Button2,Button3);

  • These parameters that I passed will be changed the visibility

3 answers

8

All components that have visual representation inherit from the class Control.

Change your method to:

private void Visible(Control x, Control y, Control z, Control a) {

    x.Visible = true;
    y.Visible = true;
    z.Visible = true;
    a.Visible = true;  
}
  • Exactly what I wanted, thank you .

7

Complementing the @ramaral response, I think this is a good opportunity to use params.

private static void Visible(params Control[] controls)
{
    foreach(var control in controls)
        control.Visible = true;
}

Thus one can pass a variable number of controls, and avoid code repetition within the method Visible:

// uso
Visible(x, y, z, a);

More information

  • Actually, I would have thought of that, but on principle, because I don’t always know the level of knowledge of the AP, take the question code and change it as little as possible to answer. Perhaps it would be useful for you to add that it is thus possible to pass any number of parameters to the method.

  • @ramaral I agree, also support minimalist responses, "to the point". The only situation where I elaborate more the answer, is when I think the PO is trying to solve the problem in the wrong way, and then I suggest a completely different approach. I think this time was an exception to my rule ^^

3

The problem is that you are trying to define the property on an object of the type object, and not TextBox.

You have to do the cast for the type you want, for example:

((TextBox)x).Visible = true;

or

((Button)y).Visible = true;
  • The answer from above resolved , thanks for the attention

Browser other questions tagged

You are not signed in. Login or sign up in order to post.