场景

通过数据库查询出来的数据为DataTable,将其设置为DataGridView的数据源。

但是查询出来的数据某一列可能不是想要展示的格式。

比如某DataTable的第三列的数据都是如下格式

C#中更改DataTable某列的值,格式化显示指定列的数据_赋值

 

 

而我们想要展示的格式如下

C#中更改DataTable某列的值,格式化显示指定列的数据_赋值_02

 

 

实现

将DataTable传递到工具类方法中



public static void ConvertComponentsToText(DataTable table)
{
for (int i = 0; i < table.Rows.Count; i++)
{
//获取原来每行第三列的数据
string oldNum = table.Rows[i][2].ToString();
//将其分隔
string[] arrayNum = oldNum.Split(',');
string Text = "";
//循环取每个数字
foreach (string b in arrayNum)
{
//通过全局键值对字典获取对应的中文Value
string name = Global.ComponentsKeyValue.Where(q => q.Key == b).First().Value.ToString();
Text += name;
Text += ",";
}
//截取,去掉最后一个逗号
Text = Text.Substring(0, Text.Length - 1);
//给当前行的地三列赋值
table.Rows[i][2] = Text;
}
}


 

上面是通过table.Rows[i][2].ToString()循环获取每行的第三列并通过 table.Rows[i][2] = Text将新的值赋值回去。

其中Global.ComponentsKeyValue全局键值对字典的内容如下

首先新建全局变量类Global,然后声明全局字段来存取键值对。



Dictionary<string, string> _componentsKeyValue = new Dictionary<string, string>()
{
{"1", "霸道"},
{"2", "流氓"},
{"3", "气质"},
{"4", "你好"},
{"5", "下午好"},
{"6", "嗯呢"}
};


然后再新建全局属性来获取此键值对



public Dictionary<string, string> ComponentsKeyValue
{
get
{
return this._componentsKeyValue;
}
}