在DataGridView单元格中修剪空格

时间:2017-07-27 18:11:19

标签: c# winforms visual-studio datagridview trim

情况/问题

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

知识

我知道Trim()会删除所有尾随空格和前进空格(" ###" - >" ###")并且只删除'似乎理解一个被修剪过的空间的单元格如何不等于""。不幸的是,我不能使用.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
   }

最大的问题是,当单元格中存在奇异空格时,因为当我尝试使用.ToString()时,它会抛出错误"输入字符串的格式不正确"。

提前致谢

1 个答案:

答案 0 :(得分:1)

我无法复制您的问题。虽然这有效但它可以处理单个空格以及空字段。

您发布的代码与我的代码之间的主要区别在于:

此致

  

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; }
    }
}
相关问题