熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

Datatbel和string之間的相互轉換

2022-06-13   來源: .NET編程 

  今天在做一個需求的時候需要將datatable轉化string下面是二者之間的一個可逆轉換

  Datatable 到 string

  public static string DataTableToString(DataTable dt)
        {
            //!@&#$%^&*為字段的拼接字符串
            //為了防止連接字符串不在DataTable數據中存在特意將拼接字符串寫成特殊的字符!
            StringBuilder strData = new StringBuilder();
            StringWriter sw = new StringWriter();

  //DataTable 的當前數據結構以 XML 架構形式寫入指定的流
            dtWriteXmlSchema(sw);
            strDataAppend(swToString());
            swClose();
            strDataAppend(@&@);
            for (int i = ; i < dtRowsCount;i++)             //遍歷dt的行
            {
                DataRow row = dtRows[i];
                if (i > )                                    //從第二行數據開始加上行的連接字符串
                {
                    strDataAppend(#$%);
                }
                for (int j = ; j < dtColumnsCount; j++)    //遍歷row的列
                {
                    if (j > )                                //從第二個字段開始加上字段的連接字符串
                    {
                        strDataAppend(^&*);
                    }
                    strDataAppend(ConvertToString(row[j])); //取數據
                }
            }

  return strDataToString();
        }

  string 到Datatable

  public static DataTable StringToDataTable(string strdata)
        {
            if (stringIsNullOrEmpty(strdata))
            {
                return null;
            }
            DataTable dt = new DataTable();
            string[] strSplit = {@&@};
            string[] strRow = {#$%}; //分解行的字符串
            string[] strColumn = {^&*}; //分解字段的字符串

  string[] strArr = strdataSplit(strSplit StringSplitOptionsNone);
            StringReader sr = new StringReader(strArr[]);
            dtReadXmlSchema(sr);
            srClose();

  string   strTable = strArr[]; //取表的數據
            if (!stringIsNullOrEmpty(strTable))
            {
                string[] strRows = strTableSplit(strRow StringSplitOptionsNone); //解析成行的字符串數組
                for (int rowIndex = ; rowIndex < strRowsLength; rowIndex++) //行的字符串數組遍歷
                {
                    string vsRow = strRows[rowIndex]; //取行的字符串
                    string[] vsColumns = vsRowSplit(strColumn StringSplitOptionsNone); //解析成字段數組
                    dtRowsAdd(vsColumns);
                }
            }
            return dt;
        }


From:http://tw.wingwit.com/Article/program/net/201311/13183.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.