1

Visual Basic 2010 .NET,DataGridView,两列。当用户单击、选择或将焦点放在第 0 列中的单元格时,想要强制第 1 列选择。

If Me.DGV.Rows.Count > 0 Then
    If Me.DGV.CurrentCell.ColumnIndex = 0 Then                       ' if ColumnIndex 0
        Me.DGV.Item(1, Me.DGV.CurrentCell.RowIndex).Selected = True  ' change ColumnIndex to 1
    End If
End If

如果不引发异常,代码示例在任何 Cell 事件中都不起作用。它在 Button 后面完美运行,但我需要在用户与 DGV 交互时运行此代码?

DGV 的“CellClick”事件很有效。当我按住鼠标按钮时,将指针移动到上方或下方的行并释放鼠标按钮,它会搞砸

Private Sub DGV_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV.CellClick
    If Me.DGV.Rows.Count > 0 Then
        If e.ColumnIndex = 0 Then
            Me.DGV.Item(1, e.RowIndex).Selected = True
        End If
    End If
End Sub

DGV 的“单击”事件按我想要的方式工作,但是在更改列索引编号时网格会闪烁?

Private Sub DGV_Click(sender As Object, e As System.EventArgs) Handles DGV.Click
    If Me.DGV.Rows.Count > 0 Then
        If Me.DGV.CurrentCell.ColumnIndex = 0 Then
            Me.DGV.Item(1, Me.DGV.CurrentCell.RowIndex).Selected = True 'This line causes a subtle 'flicker'
        End If
    End If
End Sub
4

1 回答 1

1

以下示例代码片段可以执行所需的操作(来源:http: //msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick.aspx)。请注意与您的问题相关的e.RowIndexe.ColumnIndex属性:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (turn.Text.Equals(gameOverString)) { return; }

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

    if (cell.Value == blank)
    {
        if (IsOsTurn())
        {
            cell.Value = o;
        }
        else
        {
            cell.Value = x;
        }
        ToggleTurn();
    }
    if (IsAWin())
    {
        turn.Text = gameOverString;
    }
}
于 2013-05-09T17:53:39.733 回答