Rose
Rose

Reputation: 641

How to change ColumnIndex in DataGridView when user selects a cell in Column 0

Visual Basic 2010 .NET, DataGridView, two columns. Want to force column 1 to Selected when user clicks, selects or puts focus one a cell in Column 0.

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

The code sample does not work inside any of the Cell events without throwing Exceptions. It works perfectly behind a Button but I need this code to run as the user interacts with the DGV??

The DGV's 'CellClick' event sort of works. When I hold the mouse button down, move pointer to rows above or below and release the mouse button it messes up

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

The DGV's 'Click' event works the way I want but the grid flickers when changing Column Index numbers?

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

Upvotes: 1

Views: 1521

Answers (1)

Alexander Bell
Alexander Bell

Reputation: 7918

Following sample code snippet could perform the required action (source: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick.aspx). Notice the e.RowIndex and e.ColumnIndex properties pertinent to your question:

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;
    }
}

Upvotes: 1

Related Questions