zoukankan      html  css  js  c++  java
  • C#中更改DataTable某列的值,格式化显示指定列的数据

    场景

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

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

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

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

    注:

    博客主页:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    将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;
                    }
                }
  • 相关阅读:
    ES6新语法之---块作用域let/const(2)
    sass变量
    Ruby(或cmd中)输入命令行编译sass
    sass的安装
    鼠标滚动兼容
    HTML5新标签兼容——> <!--<if lt IE 9><!endif-->
    #include stdio.h(7)
    #include stdio.h(6)
    #include stdio.h(5)
    #include stdio.h(3)
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/12753094.html
Copyright © 2011-2022 走看看