Jean Col
Jean Col

Reputation: 552

How to manage with dynamic CheckBox in C# WPF application?

I created a checkbox list with 8 chechboxes added dynamically. The idea of my program is : when a box is checked, a chart appears on my plotter, when i uncheck it, it disappears.

My problem is that I dont know how to manage the events to do that because I added the checkboxes dynamically and I need 8 different events for 8 different charts.

Thanks.

Upvotes: 1

Views: 2638

Answers (3)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can use one event for all of them. And inside of the event you will get the name of the control, which fired the event. Something like this:

 private void CheckBox_Click(object sender, RoutedEventArgs e)
 {
     CheckBox senderChk = sender as CheckBox;
     switch (senderChk.Name)
     {
         case "checkBox1":  //do something 
         case "checkBox2":  //do something 
     }
 }

Upvotes: 2

Sten Petrov
Sten Petrov

Reputation: 11040

An answer here suggests using .Name property but for dynamically-created checkboxes that may now work well.

CheckBox chx;
chx.Tag = "Chart 1"; // put these tags in an enum or at least constants
chx.Click += chx_Click; 

void chx_Click(object sender, RoutedEventArgs e)
{
    CheckBox chx = sender as CheckBox;
    if (chx != null && chx.Tag != null)
    {
        switch (chx.Tag)
        {
            case "Chart 1": 
                        myChart1.Visibility = chx.IsChecked? Visibility.Visible: Visibility.Collapsed;  
                break;
            case "Chart 2": //...
                break;
            default:
                break;
        }
    }
}

Upvotes: 1

Immortal Blue
Immortal Blue

Reputation: 1700

The "sender" parameter of the event handler indicates which control raised an event.

Somewhere, you create a control. Make sure you keep a reference to it somewhere, either as a member variable, in a dictionary or whatever.

Then, in your event handler, do the following:

If(sender==myControl)
{
   ...do something...
}
Elseif (sender==myOtherControl)
{
    ...do something else...
}

Upvotes: 0

Related Questions