Search code examples
c#vb.netwinformsexceptioncode-conversion

Why do I get this exception when clicking on a cell of a datagridview in winform in C#?


I have a code in vb.net which i want to use in C#. The code is:

Dim cell As DataGridViewImageCell = CType(tempGrid.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewImageCell)

I am trying to get corresponding C# code:

public void gridmouseclick(object sender, MouseEventArgs e)
    {
        int i;
        DataGridViewCell cell;

        for (i = 0; i <= 1 - 1; i++)
        {
            cell = (DataGridViewCell)grid[i].Rows[e.X].Cells[e.Y];   
            if (e.Button == MouseButtons.Left)
            {
                cell.Value = imglst.Images[1];
            }
            else if (e.Button == MouseButtons.Right)
            {
                cell.Value = imglst.Images[0];
            }
        }
    }

imglst is a ImageList so now I am getting an exception when I am clicking on the grid cell the exception is:

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

I am assigning the gridmouseclick like this....

grid[i].CellMouseClick += new DataGridViewCellMouseEventHandler(this.gridmouseclick);

How do I get rid of this exception?


Solution

  • Here it is in C#:

    DataGridViewImageCell cell = (DataGridViewImageCell)tempGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
    

    Key points:

    1. CType(SourceObject, TargetType) cast is written as (TargetType)SourceObject.
    2. Indexing Object(index) is written with square brackets Object[index]
    3. Dim ObjectName as Type declaration is written as Type ObjectName