4

I have create a button in code behind , but how do i write their click event? is it MouseDown? like this ? Basically i want to detect if the button is being pressed then i populate a textbox with some text.

Button btn1 = new Button();
btn1.Content = qhm.Option1;
sp1.Children.Add(btn1);

if (btn1.MouseDown = true)
{
   tbox.Text = qhm.Option1;
}
0

6 Answers 6

9

Like that:

Button btn1 = new Button();
btn1.Content = qhm.Option1;
btn1.Click += btn_Click;
sp1.Children.Add(btn1);


//separate method
private void btn_Click(object sender, RoutedEventArgs e)
{
    tbox.Text = qhm.Option1;
}

using lambda:

btn1.Click += (source, e) =>
{    
    tbox.Text = qhm.Option1;
};

you can now access local variables.

Sign up to request clarification or add additional context in comments.

Comments

1
..
btn1.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    ...
}

Comments

1

Register a handler for the click event:

btn1.Clicked += myHandler_Click;
private void myHandler_Click(object sender, RoutedEventArgs e)
{
  // your code
}

Comments

1

You want to subscribe to the click event:

Button btn1 = new Button();
btn1.Content = "content";
btn1.Click+=btn1_Click;
sp1.Children.Add(btn1);

private void btn1_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("You clicked it");
}

Comments

1

What you are looking, can be achieved with no other than Events, find in the MSDN explanations about events and how can be used.

In C# there are several kinds of GUI Controls, like Button Control, that has a number of events, like for example: click, mouseover, mousedown, doubleclick etc. In the MSDN help you can find the list of events supported for every control, along with the properties and methods.

So in your case, you'll probably want something along the line,

private void Form1_Load(object sender, EventArgs e)
{
    Button button2 = new Button();
    //Load button in container


    //Loading events for control
    button2.Click += new EventHandler(button2_Click);
}

private void button2_Click(object sender, EventArgs e)
{
    //Do Something
}

So basically button2.Click += new EventHandler(button2_Click);, you are adding and EventHandler that points to button2_click, to the Click event of the newly created button.

Comments

1

You can add a click event like this:

Button btn1 = new Button();
btn1.Content = qhm.Option1;
sp1.Children.Add(btn1);
btn1.Click += btn1_Click;
        

Than you can edit the event method to add some text to your text box.

void btn1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
           tbox.Text = qhm.Option1;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.