我有一个按钮,我必须在该按钮上调用 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 });
}
}
}
引用资料:
关于c# - 如何从按钮单击调用 Gridview 单元格单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196340/