0

I have some code on (C# WINFORM)

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
  // How to find out?
}

And I also call that event on Form_Load:

myGrid_CellClick(dgvDropsToVal, new DataGridViewCellEventArgs(0, 0));

How to find out that real mouse click occurred or it's triggered from Form_Load inside myGrid_CellClick?
Other then bool Flag on Form_Load.

  • 3
    You shouldn't call your event like that. Instead extract out the code/logic in your event to a separate method, and then Call the method from your Form_Load and your event. You would even be able to pass a flag indicating whether the call was from event or Form_Load. – Habib Apr 22 '14 at 15:34

4 Answers4

2

Add a helper method:

private void myForm_Load(object sender, EventArgs e)
{
    DoSomething(false);
}

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DoSomething(true);
}

private void DoSomething(bool wasClicked)
{
}
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
0

Why do you call the event handler method manually? It will confuse other programmers. Create seperate method and make the intent clear. Write code keeping in my you're not the only consumer of your code.

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
  CellClickAction(parameter);
}

private void CellClickAction(Whatever parameter)
{
   //Do whatever
}

And in form load you may call the same method.

private void form_Load(object sender, EventArgs e)
{
     CellClickAction(parameter);//parameter will say the source of method call
}

Now you can modify Whatever parameter to differentiate the source of method call. This makes the code clear.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

I would use a helper method with a flag since that does not add overhead. If you insist on bad programming practice then you can look at the StackFrame or use the CallerMemberNameAttribute.

See: How do I get the calling method name and type using reflection?

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

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DoSomething();
}

private void DoSomething([CallerMemberName] string caller = "")
{
    // caller will contain "myForm_Load" or "myGrid_CellClick"
}

You will incur reflection overhead penalties.

Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
0

what about using the sender param?

private void myForm_Load(object sender, EventArgs e)
{
    myGrid_CellClick(null, null);
}

private void myGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (sender == null)
    {
        //called yourself in Form_Load
    }
    else
    {
        //called by control
    }
}
sasjaq
  • 761
  • 1
  • 11
  • 31
  • sorry (null, null) is not working for me . I have to use myGrid_CellClick(myGrid,new DataGridViewCellEventArgs(0, 0));, but would be nice if I could. – user3200249 Apr 22 '14 at 16:27