3

I have simple Windows Forms application (not WPF), and I have two controls on it:

  1. TrackBar
  2. NumericUpDown

I want to make some binding between them so if one of them has its value change, the other control will be updated to show the same value.

Is this possible? If so, how can I do it?

Thanks.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Yanshof
  • 9,659
  • 21
  • 95
  • 195

2 Answers2

9

Sure, it's possible. I don't know of any way to make the connection between the two controls automatic, so you'll have the write the code yourself. But don't worry, it's not difficult.

You'll first need to attach a handler to the event that is raised by each control when its value changes. Logically enough, both controls this event the same thing: ValueChanged. Then, in each event handler method, you can programmatically set the value of the other control to the new value of the first control. For example:

void myNumericUpDown_ValueChanged(object sender, EventArgs e)
{
    // Sync up the trackbar with the value just entered in the spinbox
    myTrackBar.Value = Convert.ToInt32(myNumericUpDown.Value);
}

void myTrackBar_ValueChanged(object sender, EventArgs e)
{
    // Sync up the spinbox with the value just set on the trackbar
    myNumericUpDown.Value = myTrackBar.Value;
}

Obviously for this to work correctly, you either need to make sure that the controls have the same range (maximum and minimum values), or add some error checks to the above code.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
1

Ever time one of the controls causes a change in value, its change value handler will cause a change in the other control, followed by its change handler running. But this time the values will be the same so the change handler will not fire again, thus ending a potential endless loop.

There are ways to cause only one handler to fire but they are probably not worth it.

I will point out that for a trackbar control, using the scroll event will cause the scroll handler to fire only when the user actually moves the trackbar control. If it moves as a result of code (the other controls change handler) the scroll event will NOT be triggered. So using it instead of the value changed event will help in that direction.

Its a little harder in the other direction. You would have to create a numeric up down derived class and override the UpButton and DownButton methods to capture the clicking of the up and down arrow on the control itself.