ArgumentOutOfRangeException未处理(从Form构造函数抛出)

时间:2016-11-09 01:53:22

标签: c# .net winforms datagridview

好的,所以这里有一个稍微详细的概述我正在处理的事情:

  • 我正在创建一个带有标准化树视图的表单来选择患者。
  • 从该患者中,从组合框中选择相关的工作 在两个Datagridviews的顶部。
  • 选择两个作业后,每个datagridview都会填充相关内容 授权,然后可以拖放到另一个 job的datagridview是为了重新分配它们。

稍微不那么详细的概要:

我试图在两个datagridviews之间处理一系列拖放事件。到目前为止,大部分时间都在工作,但是当从任一gridview中删除最后一行,并且表单尝试刷新时,Program.cs文件在尝试创建新表单时抛出异常对象

Program.cs文件中的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Job2JobTransfer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1()); // this is where the error gets thrown.
        }
    }
}

看起来很简单吧?这让我想知道构造函数中是否隐藏了一些我没有考虑过的东西,或者我是否因为认识到自己的错误而过于沉闷。

以下是我按照dgv1_mousedown,dgv2_dragEnter和dgv2_dragDrop的顺序为拖放事件编写的代码。反过来就是重命名的代码。

 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            int index = e.RowIndex;
            dataGridView1.DoDragDrop(dataGridView1.Rows[index], DragDropEffects.Move);
        }

        private void dataGridView2_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            int index = e.RowIndex;
            dataGridView2.DoDragDrop(dataGridView2.Rows[index], DragDropEffects.Move);
        }

        private void dataGridView1_DragEnter(object sender, DragEventArgs e)
        {
            DataGridView otherGridView = (DataGridView)sender;

            if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
            {
                if (!dataGridView1.Rows.Contains((DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow))))
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

 private void dataGridView2_DragEnter(object sender, DragEventArgs e)
        {
            DataGridView otherGridView = (DataGridView)sender;

            if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
            {
                if (!dataGridView2.Rows.Contains((DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow))))
                    e.Effect = DragDropEffects.Move;
            }
            else
                e.Effect = DragDropEffects.None;
        }

private void dataGridView2_DragDrop(object sender, DragEventArgs e)
        {
            DataGridViewRow tempRow = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
            WorkAuthorization tempAuth = new WorkAuthorization();
            tempAuth = (WorkAuthorization)tempRow.DataBoundItem;

            dataGridView2.DataSource = null;
            workAuthList2.Add(tempAuth);
            dataGridView2.DataSource = workAuthList2;

            try
            {
                dataGridView1.DataSource = null;
                workAuthList1.Remove(tempAuth);
                dataGridView1.DataSource = workAuthList1;
            }
            catch
            {
                int index = 0; //For the sake of a break point while debugging
            }

            dataGridView2.Refresh();
            dataGridView1.Refresh();
        }

我通常不会在本网站上发布内容,所以如果我在格式化或其他方面出错,我会道歉。如果是这样,请告诉我,我会尽力纠正它。如果我需要澄清某些内容或包含更多信息,也是如此。 提前感谢任何人可能提供的任何帮助/建议。

错误消息:

  

未处理的类型&#39; System.ArgumentOutOfRangeException&#39;发生在System.Windows.Forms.dll

中      

其他信息:提供的行索引超出范围。

     

StackTrace:

     System.Windows.Forms.DataGridViewRowCollection.GetRowState(Int32 rowIndex)中的

         在System.Windows.Forms.DataGridView.OnRowHeaderMouseDown(HitTestInfo hti,Boolean isShiftDown,Boolean isControlDown)          在System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)          在System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)          在System.Windows.Forms.Control.WmMouseDown(消息&amp; m,MouseButtons按钮,Int32点击)          在System.Windows.Forms.Control.WndProc(消息&amp; m)          在System.Windows.Forms.DataGridView.WndProc(消息&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)          在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)          在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.Run(Form mainForm)          at Job2JobTransfer.Program.Main()在C:\ Users \ Rhunt \ Subversion \ WindowsApps \ ContractPatients \ Job2JobTransfer \ Job2JobTransfer \ Program.cs:第19行          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()

1 个答案:

答案 0 :(得分:1)

看来dataGridView1.DoDragDrop(dataGridView1.Rows [index],DragDropEffects.Move);或者正在调用另一个,但索引无效或行是空的或类似的东西。 可能由于某种原因,在表单初始化期间调用了一个事件处理程序。您可以从设计器文件中删除事件处理程序,然后将其移动到Form.OnLoad。如果问题仍然存在,您可以在表单已加载的情况下在事件处理程序中设置加载变量和证明。

编辑:您还可以简单地检查dataGridView1和dataGridView2是否在索引处包含行:

int index = e.RowIndex;
if(dataGridView1.Rows.Count() > 0 && index <= dataGridView1.Rows.Count()) {
    dataGridView1.DoDragDrop(dataGridView1.Rows[index], DragDropEffects.Move); 
}

编辑2: 本规范对我没有任何问题:

public class WorkAuthorization
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public partial class Form1 : Form
{
    private List<WorkAuthorization> workAuthList1;
    private List<WorkAuthorization> workAuthList2;

    public Form1()
    {
        InitializeComponent();

        workAuthList1 = new List<WorkAuthorization>();
        workAuthList1.Add(new WorkAuthorization { Name = "Authorization1", Description = "Description1" });
        workAuthList1.Add(new WorkAuthorization { Name = "Authorization2", Description = "Description2" });
        workAuthList1.Add(new WorkAuthorization { Name = "Authorization3", Description = "Description3" });

        workAuthList2 = new List<WorkAuthorization>();
        workAuthList2.Add(new WorkAuthorization { Name = "Authorization4", Description = "Description4" });
        workAuthList2.Add(new WorkAuthorization { Name = "Authorization5", Description = "Description5" });
        workAuthList2.Add(new WorkAuthorization { Name = "Authorization6", Description = "Description6" });
    }

    private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        LoadAuthorizations1();
    }

    private void LoadAuthorizations1()
    {
        dataGridView1.DataSource = workAuthList1;
    }

    private void comboBox2_SelectedValueChanged(object sender, EventArgs e)
    {
        LoadAuthorizations2();
    }

    private void LoadAuthorizations2()
    {
        dataGridView2.DataSource = workAuthList2;
    }

    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        int index = e.RowIndex;
        dataGridView1.DoDragDrop(dataGridView1.Rows[index], DragDropEffects.Move);
    }

    private void dataGridView1_DragEnter(object sender, DragEventArgs e)
    {
        DataGridView otherGridView = (DataGridView)sender;

        if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
        {
            if (!dataGridView1.Rows.Contains((DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow))))
            {
                e.Effect = DragDropEffects.Move;
            }
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    private void dataGridView2_DragEnter(object sender, DragEventArgs e)
    {
        DataGridView otherGridView = (DataGridView)sender;

        if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
        {
            if (!dataGridView2.Rows.Contains((DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow))))
            {
                e.Effect = DragDropEffects.Move;
            }
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    private void dataGridView2_DragDrop(object sender, DragEventArgs e)
    {
        DataGridViewRow tempRow = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
        WorkAuthorization tempAuth = new WorkAuthorization();
        tempAuth = (WorkAuthorization)tempRow.DataBoundItem;

        dataGridView2.DataSource = null;
        workAuthList2.Add(tempAuth);
        dataGridView2.DataSource = workAuthList2;

        try
        {
            dataGridView1.DataSource = null;
            workAuthList1.Remove(tempAuth);
            dataGridView1.DataSource = workAuthList1;
        }
        catch
        {
            int index = 0; //For the sake of a break point while debugging
        }

        dataGridView2.Refresh();
        dataGridView1.Refresh();
    }
}