【问题标题】:c# DataGridView get Cells Value from Selected Rowc# DataGridView 从选定行获取单元格值
【发布时间】:2015-12-05 18:10:30
【问题描述】:

如何使这个foreach 循环的语法正确。我想从选定的行中获取每个单元格值。 我已经将选择模式设置为FullRowSelect

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
      foreach (//datagrid cell in current_selected_row) <--- proper Syntax condition
      {
           if(cell != null)
           {
                MessageBox.Show(cell.Value.ToString());
           }
      }
}

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您可以通过这种方式找到当前行:

    var row = this.dataGridView1.CurrentRow;
    

    然后拥有当前行,您可以通过以下方式之一找到单元格值

    row.Cells.Cast<DataGridViewCell>()
       .ToList()
       .ForEach(cell =>
       {
           MessageBox.Show(string.Format("{0}", cell.Value));
       });
    

    相当于:

    foreach (DataGridViewCell cell in row.Cells)
    {
        MessageBox.Show(string.Format("{0}", cell.Value));
    }
    

    或者这样

    for (int i = 0; i < row.Cells.Count; i++)
    {
        MessageBox.Show(string.Format("{0}", row.Cells[i].Value));
    }
    

    【讨论】:

    • 哇,谢谢。我使用foreach,但是''cell =>''这行是什么意思。
    • 但是当我尝试将其过滤为 if cell.value.ToString() != null 时。它抛出 System.NullReferenceException。附加信息:对象引用未设置为对象的实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多