我有一个(相当复杂的)应用程序,并且在某些罕见的情况下(特别是第一次按下某个按钮)功能
public static bool ShowDialogOk(this Form form, IWin32Window owner = null) {
return form.ShowDialog(owner) == DialogResult.OK;
抛出异常
{System.IndexOutOfRangeException: Index -1 does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.DataGridView.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
现在这个函数在崩溃之前用相同的变量调用了很多次,这让我很难说出错了。有人知道form.ShowDialog函数中IndexOutOfRangeException的可能原因吗?这样我可以更好地调试这段代码。
编辑:我注意到只从一个地方调用ShowDialogOk,如果我在这一行放置一个断点,它只在创建GUI时传递,但实际上不是在错误触发时传递。
答案 0 :(得分:-1)
就在CurrencyManager属性的位置并进行大小检查。 (它是表单类中的属性,它可能用于网格事件(行输入或输入))(假设它是一个属性,因为:CurrencyManager.get_Item(Int32 index))
var index = <somenumber>;
if(CurrencyManager.Length > 0 && index < CurrencyManager.Length) //also can be Count()
CurrencyManager[index]
else
// Do some logic when index is out of bounds.