Trim DataGridView 单元格中的空白 Space

Trim Blank Space in DataGridView Cell

SITUATION/PROBLEM

我创建了一个 DataGridView1,然后填充了一个列表。每当我单击一个单元格时,如果单元格在编辑时不包含值,它应该引用它并抛出异常。不幸的是,一些单元格是在开始时用 space (" ") 创建的,我希望能够(在离开单元格时)在它为 null and/or 和 " " 之间进行过滤。

知识

我知道 Trim() 会删除所有尾随的白色 spaces 并继续 spaces (" ### " -> "###") 并且只是不要我似乎不明白一个带有 space 的单元格是如何修剪的不等于“”。不幸的是,我不能使用 .Length() 因为单元格值也大多是 1 位整数。

当前代码

foreach (DataGridViewRow row in dataGridView1.Rows)
{
   if (row.Cells[0].Value.ToString() != null && row.Cells[0].Value.ToString().Trim() != "")
   {
      //it always hits here and passes through the conditional statement
      //contains method to set textbox equal to cell value
   }

最大的问题是每当单数 space 留在单元格中时,因为当我尝试使用 .ToString() 时它会抛出错误 "Input string was not in a correct format"。

提前致谢

我无法重现您的问题。虽然这有效并且它处理单个空格以及空字段。

你发布的代码和我的主要区别在于这部分:

你的

if (row.Cells[0].Value.ToString() != null && row.Cells[0].Value.ToString().Trim() != "")

我的

if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().Trim() != "")

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TrimBlanksInDGV_45358146
{
    public partial class Form1 : Form
    {
        public static string whatwasit = "";
        public Form1()
        {

            InitializeComponent();
            List<listitem> datasource = new List<listitem>();
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = "name1", last = "last1" });
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = "name2", last = "last2" });
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = "name3", last = "last3" });
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = "name4", last = "last4" });
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = " ", last = "last5" });
            datasource.Add(new TrimBlanksInDGV_45358146.listitem { name = "", last = "last6" });
            dataGridView1.DataSource = datasource;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().Trim() != "")
                {
                    whatwasit = "not empty or \"\"";
                }
                else
                {
                    whatwasit = "empty or \"\"";
                }
            }
        }
    }

    public class listitem
    {
        public string name { get; set; }
        public string last { get; set; }
    }
}