1. 程式人生 > >獲取單元格

獲取單元格

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