Click here to Skip to main content
15,904,024 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C#
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
C#
string MesId = dgMessages.Rows[RowAdj].Cells["clmTransMessage"].Value.ToString();


Am filling my datagridview from sql table.
Posted
Updated 25-Aug-11 18:31pm
v2

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.

C#
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();
}
 
Share this answer
 
v2
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.
 
Share this answer
 
Comments
shan1395 25-Aug-11 23:54pm    
i has a value in it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900