如何选择一个单元格的值? [英] How to select the value of a cell?

查看:90
本文介绍了如何选择一个单元格的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



Heres是我的 datagridview.Click 方法:

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

目前我的名称变量是 null

我做错了什么?



解决方案

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

以防万一,确保事件有线up:

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


I have a DataGridView, I want to select the cell of the first column.

Heres is my datagridview.Click method:

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

Currently my name variable is null.

What am I doing wrong?

解决方案

CurrentRow may not be set yet, so use the RowIndex property for the event argument. Try it this way:

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

And just in case, make sure the event is wired up:

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

这篇关于如何选择一个单元格的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆