-3

我在 vb.net 中有一个我想在 C# 中使用的代码。代码是:

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

我正在尝试获取相应的 C# 代码:

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是的ImageList,所以现在当我单击网格单元格时出现异常,异常是:

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

我正在分配gridmouseclick这样的......

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

我该如何摆脱这个异常?

4

3 回答 3

0

这是在 C# 中:

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

关键点:

  1. CType(SourceObject, TargetType)cast 写为(TargetType)SourceObject.
  2. 索引Object(index)是用方括号写的Object[index]
  3. Dim ObjectName as Type声明写成Type ObjectName
于 2012-09-15T06:30:56.310 回答
0

简单的

DataGridViewImageCell cell = 
(DataGridViewImageCell)tempGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
于 2012-09-15T06:38:37.753 回答
0

请更改类型:

DataGridViewImageCell cell =  (DataGridViewImageCell)tempGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
于 2012-09-15T07:29:23.950 回答