我有一个按钮,我必须调用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
}
答案 0 :(得分:0)
您无法提出其他课程事件。事件实际上是作为私人代表编写的。但您可以通过反射或控制继承来实现。
在Control Inheritance中,您必须首先从目标控件(DataGridView)继承,然后定义一个方法来调用您需要运行它的Event。
换句话说,您只需找到私有委托字段,获取它,然后调用它:
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 });
}
}
}
参考文献:
答案 1 :(得分:0)
例如,我按名称 MySharedClass 创建了一个静态类:
using System.Reflection;
namespace WindowsFormsApplication1
{
public static class MySharedClass
{
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 });
}
}
}
}
}
然后,在视图层代码中,例如在按钮上单击事件会引发:
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Raise("Click", new EventArgs());
}