방법: Windows Forms DataGridView 컨트롤에서 현재 셀 가져오기 및 설정

DataGridView와 상호 작용하려면 종종 프로그래밍 방식으로 현재 활성 상태인 셀을 검색해야 합니다. 현재 셀을 변경해야 할 수도 있습니다. CurrentCell 속성을 사용하여 이러한 작업을 수행할 수 있습니다.

참고

Visible 속성이 false로 설정된 행이나 열에서 현재 셀을 설정할 수 없습니다.

DataGridView 컨트롤의 선택 모드에 따라 현재 셀을 변경하면 선택 영역이 변경됩니다. 자세한 내용은 Windows Forms DataGridView 컨트롤의 선택 모드를 참조하세요.

프로그래밍 방식으로 현재 셀을 가져오려면

  • DataGridView 컨트롤의 CurrentCell 속성을 사용합니다.

    private void getCurrentCellButton_Click(object sender, System.EventArgs e)
    {
        string msg = String.Format("Row: {0}, Column: {1}",
            dataGridView1.CurrentCell.RowIndex,
            dataGridView1.CurrentCell.ColumnIndex);
        MessageBox.Show(msg, "Current Cell");
    }
    
    Private Sub getCurrentCellButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles getCurrentCellButton.Click
    
        Dim msg As String = String.Format("Row: {0}, Column: {1}", _
            dataGridView1.CurrentCell.RowIndex, _
            dataGridView1.CurrentCell.ColumnIndex)
        MessageBox.Show(msg, "Current Cell")
    
    End Sub
    

프로그래밍 방식으로 현재 셀을 가져오려면

  • DataGridView 컨트롤의 CurrentCell 속성을 설정합니다. 다음 코드 예제에서 현재 셀은 행 0, 열 1로 설정됩니다.

    private void setCurrentCellButton_Click(object sender, System.EventArgs e)
    {
        // Set the current cell to the cell in column 1, Row 0.
        this.dataGridView1.CurrentCell = this.dataGridView1[1,0];
    }
    
    Private Sub setCurrentCellButton_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles setCurrentCellButton.Click
    
        ' Set the current cell to the cell in column 1, Row 0. 
        Me.dataGridView1.CurrentCell = Me.dataGridView1(1, 0)
    
    End Sub
    

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • getCurrentCellButtonsetCurrentCellButton이라는 두 개의 Button 컨트롤. Visual C#에서는 각 단추에 대한 Click 이벤트를 예제 코드의 연결된 이벤트 처리기에 연결해야 합니다.

  • dataGridView1이라는 DataGridView 컨트롤

  • SystemSystem.Windows.Forms 어셈블리에 대한 참조

참고 항목