Ivan
Ivan

Reputation: 1171

How to hide dynamically created button?

I have a button that is created dynamically in C#. Now I want this button to hide when it is clicked. How would I do this?

I tried this, but it doesn't work:

 if (hide_button.Click == true)
                {
                    hide_button.Visibility = Visibility.Hidden;
                }

Upvotes: 0

Views: 939

Answers (2)

Sophie Coyne
Sophie Coyne

Reputation: 1006

button.Click += (sender,e) => 
    {
        if (button.Visibility == Visibility.Visible)
            button.Visibility = Visibility.Collapsed;
        else
            button.Visibility = Visibility.Visible;
    };

or

button.Click += new EventHandler(button_Click);

private void button_Click(object sender, EventArgs e)
{
    if (button.Visibility == Visibility.Visible)
        button.Visibility = Visibility.Collapsed;
    else
        button.Visibility = Visibility.Visible;
}

Upvotes: 0

Abin
Abin

Reputation: 2956

I am not sure the below line works for you.

if (hide_button.Click==true)

try removing this line and it will work. as the event is not equatable to a Boolean value.

This code worked for me

Button buton = new Button();
    public MainWindow()
    {
        InitializeComponent();            
        buton.Click += Buton_Click;
        grid.Children.Add(buton);
    }

    private void Buton_Click(object sender, RoutedEventArgs e)
    {
        buton.Visibility = Visibility.Hidden;
    }

Upvotes: 1

Related Questions