调用函数 c# 中的事件
本文关键字:事件 函数 调用 | 更新日期: 2023-09-27 18:33:08
如何在函数中调用事件?因为我Object reference not set to instance of an object
错误,错误指向:_e.RowIndex
我想知道如何在函数中调用事件。现在我能做的是从new EventHandler(....)
调用一个事件,但现在我想在函数中调用一个事件,它给了我错误Object reference not set to instance of an object
这是代码:
private void UpdateQuantityDataGridView(object sender, EventArgs e)
{
DataGridViewCellEventArgs _e = null;
cmdSelect.Parameters.Add( "ProductCode" , System.Data.OleDb.OleDbType.VarChar ) ;
cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product Code" , _e.RowIndex].Value;
}
上面的代码是正确的方法吗?
编辑
这就是我调用函数UpdateQuantityDataGridView
的地方:
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(@"C:'Windows'Media'Windows Exclamation.wav");
_sounds.Play();
MessageBox.Show("Updated Successfully!", "Updated");
ShowButtons(sender, e);
DisableColumnEdited(sender, e);
UpdateQuantityDataGridView(sender, e);
}
这是我的情况:
当用户在 DataGridView 中编辑数据,并且用户单击"确定"按钮时,上面的代码将执行并从 DataGridView 更新数据库,这就是我想在函数内访问DataGridViewCellEventArgs
的原因。当我使用
变量_e设置为 null。然后,您在从未设置时引用_e.RowIndex。
您正在将_e
设置为null
然后尝试使用它来创建NullReferenceException
(正如您所发现的那样)。
我认为您想将e
转换为DataGridViewCellEventArgs
而不是创建新变量。
private void UpdateQuantityDataGridView(object sender, EventArgs e)
{
cmdSelect.Parameters.Add( "ProductCode" , System.Data.OleDb.OleDbType.VarChar ) ;
cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product Code" , ((DataGridViewCellEventArgs)e).RowIndex].Value;
}
(如注释中所述,这假设您正在传递e
的DataGridViewCellEventArs
实例。
您正在将_e
设置为null
。
然后,您尝试访问其RowIndex
属性,这就是抛出NullReferenceException
的原因。
您的代码示例尝试执行的所有操作是向cmdSelect
添加一个参数。你到底想完成什么?