Sheldon Sheldon - 3 months ago 43
C# Question

How to call a Gridview cell click Event from button Click

I have a button on which I have to Call an event of Gridview can anyone help how can I do this functionality. my code is below
what can do ?

DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
col1.HeaderText = "Variance";
col2.HeaderText = "Tolerance";
col3.HeaderText = "Flags";

if (e.ColumnIndex == 5 || e.ColumnIndex == 6)
{
double ActualWeight;
double TargetWeight;

object val1 = dataGridView2.Rows[e.RowIndex].Cells[5].Value;
object val2 = dataGridView2.Rows[e.RowIndex].Cells[6].Value;

if (val1 != null && val2 != null
&& double.TryParse(val1.ToString(), out ActualWeight)
&& double.TryParse(val2.ToString(), out TargetWeight))
{
dataGridView2.Rows[e.RowIndex].Cells[0].Value =Math.Round (ActualWeight-TargetWeight);
}
else
{
dataGridView2.Rows[e.RowIndex].Cells[0].Value = "Invalid Numbers";
}
}


protected void bUpdate_Click(object sender, EventArgs e)
{
// I have to call Gridview Event here
}

Answer

You can't raise another classes events. Events are really written as a private delegate. But you can do it via Reflection or Control Inheritance.

In Control Inheritance you must be first inherit from your target controls (DataGridView) and so define a method to call that Event which you need to run it.

In other way, you simply need to find the private delegate field, get it, then invoke it:

public static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
    {
        var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
        if (eventDelegate != null)
        {
            foreach (var handler in eventDelegate.GetInvocationList())
            {
                handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });
            }
        }
    }

References:

The following code example shows how to load an assembly, create an instance of a type from the assembly, create an event handler using a dynamic assembly, and hook up the dynamic event handler. All actions are performed using late binding.

How to: Hook Up a Delegate Using Reflection

How do I raise an event via reflection in .NET/C#?