如果单元格为空,如何删除逗号? [英] How to Remove comma if the cell is empty?

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

问题描述

这是我的代码



This is my code

e.Row.Cells[1].Text = e.Row.Cells[1].Text +","+ e.Row.Cells[2].Text + "," + e.Row.Cells[3].Text;





这里是在gridview上合并三个单元格。

但是如果任何单元格为空则会出现逗号问题,那么逗号也会打印



喜欢

我们,英国,(正确)

我们,(像我一样)



请给我解决这个问题的方法。



here am merging three cells on gridview .
but am getting problem with comma if any cell is empty then also comma is printing

like
us,uk,(correct)
us, ,(like am getting)

Please give me solution for this problem.

推荐答案

这样的事情可能会起到作用:



Somthing like this might do the job:

private string CellCombination(IEnumerable<string> values)
{
	string result = "";
	foreach (string s in values)
	{
		if (!string.IsNullOrWhiteSpace(s)) result += string.Format("{0},", s);
	}

	return result.Trim(',');

}</string>





或者使用Linq同样的事情





Or the same thing using Linq

private string CellCombination(IEnumerable<string> values)
{
    string result = values.Where(s => !string.IsNullOrWhiteSpace(s)).Aggregate("", (current, s) => current + string.Format("{0},", s));

    return result.Trim(',');

 }





要使用它,只需将您的单元格作为可枚举集合传入函数。



所以这样的事情:





To use it, just pass in your cells into the function as an enumerable collection.

So something like this:

e.Row.Cells[1].Text = CellCombination(new [] {e.Row.Cells[1].Text, e.Row.Cells[2].Text, e.Row.Cells[3].Text });


e.Row.Cells[1].Text = e.Row.Cells[1].Text + (string.IsNullOrEmpty(e.Row.Cells[2].Text) ? string.empty : ",") + e.Row.Cells[2].Text + (string.IsNullOrEmpty(e.Row.Cells[3].Text) ? string.empty : ",") + e.Row.Cells[3].Text;


e.Row.Cells[1].Text = e.Row.Cells[1].Text + ((e.Row.Cells[2].Text.ToString().Trim().Length>0)?  ("," + e.Row.Cells[2].Text) : string.Empty )+  ((e.Row.Cells[3].Text.ToString().Trim().Length>0) ?  ("," + e.Row.Cells[3].Text) : string.Empty );



快乐编码!

:)


Happy Coding!
:)


这篇关于如果单元格为空,如何删除逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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