索引超出范围:Datagridview [英] Index was out of range : Datagridview

查看:90
本文介绍了索引超出范围:Datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想我在代码中搞砸了,当单元格单击时,它总是抛出该异常

索引超出范围.必须为非负数,并且小于集合的大小.
参数名称:索引"

这是我的代码

Hi All,

I think i screwed up something in my code,it throws this exception all the time when the cell clicked

"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

here is my code

void dgMessages_CellClick(object sender, DataGridViewCellEventArgs e)
     {

         //try
         //{
             // Ignore clicks that are not on button cells.
             if (e.RowIndex < 0 || e.ColumnIndex != dgMessages.Columns["clmMessageId"].Index) return;
             //// Retrieve the Row Index
             string RowId = dgMessages[0, e.RowIndex].Value.ToString();

             //// convert string to Interger
             int RowIndex;
             int.TryParse(RowId, out RowIndex);
             //Row Index calculation here
             int RowAdj = RowIndex - 1;
             //Retrive the Error Queue Message for that particular Row Index
              string MesId = dgMessages.Rows[RowAdj].Cells["clmTransMessage"].Value.ToString();



这是引发异常的地方



this is where it throw''s exception

string MesId = dgMessages.Rows[RowAdj].Cells["clmTransMessage"].Value.ToString();



我正在从sql表填充我的datagridview.



Am filling my datagridview from sql table.

推荐答案

当您尝试访问网格中不可用的行/单元格并且使用
int RowAdj = RowIndex - 1;在您的代码中,您需要设置以下条件以避免这种情况.

Index out of range error comes when you try to access row/cell not available in grid and as you use
int RowAdj = RowIndex - 1; in your code you need to put below condition to avoid this.

if (RowIndex > 0)
{
   int RowAdj = RowIndex - 1;
   //Retrive the Error Queue Message for that particular Row Index
   string MesId = dgMessages.Rows[RowAdj].Cells["clmTransMessage"].Value.ToString();
}


在分配之前,您可以验证特定单元格是否具有值.

Before the assignment, you can validate whether the particular cell has the value or not.

if (dgMessages.Rows[RowAdj].Cells["clmTransMessage"].HasValue)
{
   String MesId=dgMessages.Rows[RowAdj].Cells["clmTransMessage"].Value.ToString();
}



使用更安全的代码来避免索引超出范围错误.



Itz safer code to avoid index out of range error.


这篇关于索引超出范围:Datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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