c# - 如何从按钮单击调用 Gridview 单元格单击事件

标签 c# .net winforms

我有一个按钮,我必须在该按钮上调用 Gridview 的事件,任何人都可以帮助我如何实现此功能。我的代码在下面 可以做什么?

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
}

最佳答案

您不能引发其他类事件。事件实际上是作为私有(private)委托(delegate)编写的。但您可以通过反射控制继承来实现。

在控件继承中,您必须首先从您的目标控件 (DataGridView) 继承,因此定义一个方法来调用您需要运行它的事件。

换句话说,您只需找到私有(private)委托(delegate)字段,获取它,然后调用它:

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 });
            }
        }
    }

引用资料:

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#?

关于c# - 如何从按钮单击调用 Gridview 单元格单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196340/

相关文章:

c# - 我应该使用哪个类将二进制数据写入缓冲区(比如字节列表)

c# - 如何在 C# 中的列表框中插入复选框?

c# - .NET HBase REST API 客户端库 - 从 MVC5 Controller 调用

c# - REGEX 返回字符串中所有大写短语的列表

c# - MSTest:没有运行测试,因为没有加载测试或禁用了选定的测试

c# - .net 核心模拟 dbcontext 不工作(静态问题?)

c# - IEnumerable<T> 问题

c# - 在 C++ 中调用 C# dll

c# - 如何从 Windows 窗体中的给定 url 下载文件到特定路径?

c# - 将 XML 元素读取到 ListView - 我如何将两个变量传递给方法