如何处理此异常:索引超出范围。必须是非负数且小于集合的大小。参数名称:index [英] How to handle this exception:Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

查看:161
本文介绍了如何处理此异常:索引超出范围。必须是非负数且小于集合的大小。参数名称:index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void Daily_Attendance_Load(object sender, EventArgs e)
{
      DataTable dailyattendance = new DataTable();
      dailyattendance = emp.viewallemployee(); //Function  for selecting all data from table
     for (int i = 0; i < dailyattendance.Rows.Count; i++)
     {
         dataGridView1.Rows[i].Cells[0].Value = dailyattendance.Rows[i][0].ToString();                 
         dataGridView1.Rows[i].Cells[1].Value = dailyattendance.Rows[i][1].ToString();
         dataGridView1.Rows[i].Cells[2].Value = dailyattendance.Rows[i][2].ToString();
         dataGridView1.Rows[i].Cells[3].Value = dailyattendance.Rows[i][3].ToString();
     }
}

推荐答案

如果您使用DataTable,最简单的方法是将dataTable与datagridview绑定即

If you are using DataTable the simplest method is Binding the dataTable with your datagridview i.e
datagridView.DataSource = dailyAttendance;



你可以在这里找到很多文章在关于如何将dataTable绑定到datagridview的代码项目中,有一个是关于datagridview的重要事实 [< a href =http://www.codeproject.com/Articles/389811/Important-facts-about-datagridviewtarget =_ blanktitle =New Window> ^ ]



现在回到索引超出范围异常时,可能是当您尝试访问行,datagirview的单元格或dataTable行或单元格时未解释你的问题。调试你的应用程序,以确定哪个变量抛出此异常datagrid或dataTable并添加要匹配的列。



我最初的想法是你忘了在之前添加datagridviewRow实例到行你访问''dataGridView1.Rows [i]''


You can find numerous article here in code project on how to bing dataTable to datagridview one is Important facts about datagridview[^]

Now coming back to the "Index was out of range" exception it may be when you try to access the row, the cells of the datagirview or the dataTable rows or cells which is not explained in your question. debug your application to identify which variable throws this exception datagrid or dataTable and add the columns to match.

my initial thought is you forget to add datagridviewRow instance to the Rows before you access ''dataGridView1.Rows[i]''


在不知道错误发生在哪一行的情况下,我们无法帮助你找到具体的答案。

最好的(实际上只有)解决方案是使用调试器。

在方法的第一行放置一个断点:

Without knowing which exact line the error occurs on, we can''t help you with a specific answer.
The best (indeed pretty much only) solution is to use the debugger.
Put a breakpoint on the first line in the method:
DataTable dailyattendance = new DataTable();

然后单步执行。

您可以检查每个步骤的每个变量并确定应该发生什么,然后将其与实际运行时发生的情况进行比较这条线。



只有这样你才能获得足够的信息才能开始解决这个问题!

And single step though it.
You can examine each variable at each step and decide what should happen, then compare that with what did happen when you actually run the line.

Only then will you have anywhere near enough information to start solving this!


这篇关于如何处理此异常:索引超出范围。必须是非负数且小于集合的大小。参数名称:index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆