简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM