获取单元格

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//获取行号索引

//第一种方式
//int row = e.RowIndex + 1;
//int col = e.ColumnIndex + 1;

//第二种方式
//int row = dataGridView1.CurrentCell.RowIndex + 1;
//int col = dataGridView1.CurrentCell.RowIndex + 1;

//第三种方式
int row = dataGridView1.CurrentCellAddress.Y + 1;
int col = dataGridView1.CurrentCellAddress.X + 1;
int col2 = dataGridView1.CurrentCellAddress.X + 2;

//获取单元格的内容
//第一种方式
//获取第几行第几列的值
string cell2 = dataGridView1.Rows[row - 1].Cells[col - 1].Value.ToString();
string cell3 = dataGridView1.Rows[row - 1].Cells[col2 - 1].Value.ToString();
label1.Text = cell2;
label2.Text = cell3;

//第二种方式
string cell = dataGridView1.CurrentCell.Value.ToString();
MessageBox.Show("您点击的是第" + row.ToString() + "行,第" + col.ToString() + "列\n"+"获取的值是:"+cell);
}

猜你喜欢

转载自www.cnblogs.com/wangjinya/p/9933054.html