場景
通過數據庫查詢出來的數據為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; } }