Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger an event handler from within another event, C#

So I have a form where I want to change the position of a trackbar and trigger the trackbar_scroll event after I click on a label. So far, clicking on the label changed the value of the trackbar, thats easy:

        private void label4_Click(object sender, EventArgs e)
        {
            trackBar1.Value = 0;
        }
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            if (trackBar1.Value == 0)
            {
                try
                {
                    //code...
                }
                catch
                {
                    MessageBox.Show("Error occured");
                }
            }
        }

How do I call the trackBar1_scroll(..) event from within the label click?

like image 770
fifamaniac04 Avatar asked Dec 09 '22 01:12

fifamaniac04


2 Answers

Try calling it directly. You just have to supply the parameters yourself:

trackBar1_Scroll(trackBar1, EventArgs.Empty);

or simply

trackBar1_Scroll(null, null);

if the parameters are not being utilized.

like image 75
LarsTech Avatar answered Dec 11 '22 13:12

LarsTech


Another approach you could take, aside from @LarsTech answer (which is absolutely correct), would be to refactor your code to reduce the need to supply empty parameters. Since you're not actually using the EventArgs or referencing the sender directly, given your example above, you could do something like the following:

private void DoSomething(int value)
{
   ...
}

private void trackBar1_Scroll(object sender, EventArgs e)
{
   DoSomething(trackBar1.Value);
}

private void label4_Click(object sender, EventArgs e)
{
   DoSomething(...);
}

It always feels like code smell to me, when you call an event handler with empty parameters, simply to execute code which you could otherwise abstract out.

like image 28
George Johnston Avatar answered Dec 11 '22 14:12

George Johnston