728x90

C# dataGridView 에서 현재 셀의 속성을 이용하여 키보드가 Up 될(커서가 위치할) 때 해당 값을 텍스트박스로 출력하는 방법이다.



int columnIndex = dataGridView.CurrentCell.ColumnIndex;
int rowIndex = dataGridView.CurrentCell.RowIndex;

을 이용하는 것도 좋지만,

int rowIndex = dataGridView1.CurrentRow.Index; 를 사용하는게 더 좋은거 같다.

추가적으로

lbl_View1.Text = this.dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentRow.Index].Value.ToString();

현재의 셀의 값을 읽어내는 것은 dataGridView1[칼럼,행] 으로 표기된다.

이걸 잘못해서 거꾸로 적었다가 낭패를 본 적도 있다.

셀 단위로 이동할 경우 자동으로 현재의 셀 값을 읽어낸다.


private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
     int rowIndex = dataGridView1.CurrentRow.Index;

     textBox1.Text = dataGridView1.Rows[rowIndex].Cells[3].Value.ToString();
     textBox2.Text = dataGridView1.Rows[rowIndex].Cells[4].Value.ToString();
     textBox3.Text = dataGridView1.Rows[rowIndex].Cells[5].Value.ToString();
     textBox4.Text = dataGridView1.Rows[rowIndex].Cells[6].Value.ToString();
}


열(column) 의표시를 dataGridView 에서는 Cells 로 표현한다.

만약, 현재 커서가 위치한 셀의 값만 textBox1.Text 에 표시하고 싶다면


private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
     int rowIndex = dataGridView1.CurrentCell.RowIndex;

     int columnIndex = dataGridView1.CurrentCell.ColumnIndex;

     textBox1.Text = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value.ToString();
}


// 현재 dataGridView 셀의 값을 표기

if (dgv == dataGridView1)
{
    lbl_View1.Text = dgv[dgv.CurrentCell.ColumnIndex, dgv.CurrentRow.Index].Value.ToString();
}
else if (dgv == dataGridView2)
{
    lbl_View2.Text = dgv[dgv.CurrentCell.ColumnIndex, dgv.CurrentRow.Index].Value.ToString();
}



블로그 이미지

Link2Me

,