如何选择单元格的值?

时间:2013-02-28 19:06:32

标签: c# winforms datagridview

我有一个DataGridView,我想选择第一列的单元格。

Heres是我的datagridview.Click方法:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    name = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}

目前我的名字变量为null

我做错了什么?

enter image description here

3 个答案:

答案 0 :(得分:2)

可能尚未设置CurrentRow,因此请使用RowIndex属性作为事件参数。试试这种方式:

void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
  if (e.RowIndex > -1 && dataGridView1.Rows[e.RowIndex].Cells[0].Value != null) {
    name = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
  }
}

为了以防万一,请确保事件已连线:

public Form1() {
  InitializeComponent();
  dataGridView1.CellClick += dataGridView1_CellClick;
}

答案 1 :(得分:0)

你可以这样做:

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      var view = (sender as DataGridView); //<-- notes this
      var currentCellString = view.CurrentCell.Value.ToString();
    }

有时您需要抓取使用中的sender对象 - 因为它将始终更新。

答案 2 :(得分:-1)

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    object name = dataGridView1.Rows[e.RowIndex].Cells[0].Value;
    MessageBox.Show(name.ToString() == string.Empty ? "myvalue" : name.ToString());
}
相关问题