[在我的DataGridView
中,我使用DataView过滤数据表。在过滤器中使用CheckBox
值。
当未选中复选框时,该行应消失。为了立即运行它,我在AcceptChanges()
事件中使用了CurrentCellDirtyStateChanged
。 (否则,该行将保持显示状态,直到选择了另一行)。
当我用鼠标取消选中复选框时,此方法有效。 使用空格键引发NullReferenceException异常。
这里有一些示例代码:
(完全正常。只需要具有空白DataGridView1的Form1。使用空格键更改CheckBox会引发异常)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable table;
DataView view;
public Form1()
{
InitializeComponent();
Init();
}
// Building the table and view
private void Init()
{
table = new DataTable();
table.Columns.Add("check", typeof(bool));
table.Rows.Add(true);
table.Rows.Add(true);
table.Rows.Add(true);
view = new DataView(table);
view.RowFilter = "check = true";
dataGridView1.DataSource = view;
}
// CurrentCellDirtyStateChanged Event
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty == true && dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
// AcceptChanges to update the view
// works with mouse click, throws NullReferenceException when spacebar is used
table.AcceptChanges();
}
}
}
}
还有什么办法可以使其与空格键一起使用?
编辑该异常在.net运行时中的任何位置抛出,而不是由AcceptChanges()直接抛出。
System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
bei System.Windows.Forms.DataGridViewCheckBoxCell.NotifyMASSClient(Point position)
bei System.Windows.Forms.DataGridViewCheckBoxCell.OnKeyUp(KeyEventArgs e, Int32 rowIndex)
bei System.Windows.Forms.DataGridView.OnKeyUp(KeyEventArgs e)
bei System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
bei System.Windows.Forms.DataGridView.ProcessKeyEventArgs(Message& m)
bei System.Windows.Forms.Control.WmKeyChar(Message& m)
bei System.Windows.Forms.Control.WndProc(Message& m)
bei System.Windows.Forms.DataGridView.WndProc(Message& m)
bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bei Sample.Program.Main() in C:\Projects\TFS\Sample\Sample\Program.cs:Zeile 21.
在我的DataGridView中,我使用DataView来过滤DataTable。 CheckBox值用于过滤器中。取消选中CheckBox时,该行应消失。要立即运行,我使用...
以这种方式使用Invoke使代码更易于阅读,因为不需要显式的委托声明。
根据Microsoft Connect的报道,一个可能的解决方法是将CommitEdit
延迟到CellDirtyStateChanged
事件处理程序完成。