Thursday 12 March 2015

convert datatable to string in C#

 public string ConvertDataTableToString(DataTable dt, int i = 0)
        {

            string strCaption = string.Empty;
            string strDataType = string.Empty;
            DataRow drCloned;
            int colIndex;
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                strCaption = strCaption + dt.Columns[j].Caption + "#";
                strDataType = strDataType + dt.Columns[j].DataType.Name + "#";
            }

            DataTable dtCloned = dt.Clone();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                dtCloned.Columns[j].DataType = typeof(string);
            }
            foreach (DataRow row in dt.Rows)
            {
                colIndex = 0;
                drCloned = dtCloned.NewRow();
                //drCloned = row;
                foreach (DataColumn col in dt.Columns)
                {
                    if (row[col].Equals(DBNull.Value))
                    {
                        drCloned[colIndex] = string.Empty;
                    }
                    else
                    {
                        drCloned[colIndex] = row[col];
                    }
                    colIndex++;
                }
                dtCloned.Rows.Add(drCloned);
            }

            DataSet ds1 = new DataSet();
            ds1.Tables.Add(dtCloned.Copy());
            ds1.Tables[0].TableName = "Table" + i;
            string str = ds1.GetXml().ToString();
            return string.Concat(str, "*", strCaption, "*", strDataType);
        }

No comments:

Post a Comment