Search code examples
c#listeventscontrolstrackbar

C# Raise Event from List of Controls


WARNING: Embedded software delevoper trying to build PC software!

I'm trying to interface a piece of hardware that communicates with the PC via serial interface. The PC software (C#) periodicaly sends a byte array, which I would like to adjust using some trackbars.

Instead of adding 8 trackbars on the design view, I add one to help me align it and then I create a List which I populate on load like so:

public partial class FormDmxTemplate : Form
{
    // Controls
    // Create a list of tracbars.
    List<TrackBar> trackBarDmx = new List<TrackBar>();

    public FormDmxTemplate()
    {
        InitializeComponent();            
    }

    private void FormDmxTemplate_Load(object sender, EventArgs e)
    {
        // Add first instance on the list
        trackBarDmx.Add(trackBarDmx1);
        // Generate 7 more, 8 total, of each
        // Copy settings, and place them next to each other
        for (int i = 1; i < 8; i++)
        {
            // Trackbars
            trackBarDmx.Add(new TrackBar());
            trackBarDmx[i].TickStyle   = trackBarDmx[0].TickStyle;
            trackBarDmx[i].Orientation = trackBarDmx[0].Orientation;
            trackBarDmx[i].Minimum     = trackBarDmx[0].Minimum;
            trackBarDmx[i].Maximum     = trackBarDmx[0].Maximum;
            trackBarDmx[i].Size        = new System.Drawing.Size(trackBarDmx[0].Size.Width, trackBarDmx[0].Size.Height);
            trackBarDmx[i].Location    = new System.Drawing.Point(trackBarDmx[i-1].Location.X + 60, trackBarDmx[0].Location.Y);
            this.Controls.Add(trackBarDmx[i]);
        }
    }
}

Is it possible to have events for all the List members like this one?

private void trackBarDmx1_Scroll(object sender, EventArgs e)
{

}

Which means I'd like update the relevant byte in my byte array to match the TrackBar value, using events if possible.

NOTE: This is a form template which I load and close via another form.


Solution

  • You can subscribe to the events when creating the TrackBars. All can have the same event handler:

    trackBarDmx[i].Scroll += trackBarDmx1_Scroll;
    

    Then in the handler you can find out which is this TrackBar and at which index it is (if necessary)

    private void trackBarDmx1_Scroll(object sender, EventArgs e)
    {
        TrackBar bar = sender as TrackBar;
        int trackBarIndex = this.trackBarDmx.IndexOf(bar);
    }