我有一个 DataGridView
,我想选择第一列的单元格。
这是我的 datagridview.Click
方法:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
name = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
目前我的名称变量是null
。
我做错了什么?
我有一个 DataGridView
,我想选择第一列的单元格。
这是我的 datagridview.Click
方法:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
name = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
目前我的名称变量是null
。
我做错了什么?
当前行可能尚未设置,因此请使用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;
}
dataGridView1
本身为 null
,会怎样? - user586399 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var view = (sender as DataGridView); //<-- notes this
var currentCellString = view.CurrentCell.Value.ToString();
}
sender
对象并使用它,因为它总是会被更新。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());
}