form.ShowDialog(owner) throws IndexOutOfRangeException possi

本文关键字:throws IndexOutOfRangeException possi owner ShowDialog form | 更新日期: 2023-09-27 18:12:38

我有一个(相当复杂的)应用程序,在某些罕见的情况下(特别是第一次按下某个按钮),函数

    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)

现在这个函数在崩溃之前用相同的变量调用了好几次,这让我很难判断出哪里出了问题。有谁知道导致IndexOutOfRangeException的可能原因吗?ShowDialog函数?这样我就可以更好地调试这段代码了。

编辑:我注意到showdialgok只从1个地方调用,如果我在这行上放一个断点,它只在创建GUI时传递,而不是在错误触发时传递。

form.ShowDialog(owner) throws IndexOutOfRangeException possi

就在CurrencyManager属性的位置,并做一个大小检查。(它是表单类中的属性,它可能用于网格事件(行输入或其他东西))(假设它是一个属性,因为:get_Item Int32指数)

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.