Wednesday, 28 September 2016

Convert Datatable to String or Datatable to Json string


Some times we came to situation where we need to convert data to string , it may be data table to string or data set to string .To do this I have created two function

To convert into string
public String DataTable2String(DataTable dt)
    {
        StringBuilder rst = new StringBuilder();
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn col in dt.Columns)
            {
                rst.Append(row[col] + "/**/");
            }
            rst.Append("/***/");
        }
        rst.Append("/****/");
        return rst.ToString();

        //column Deliminatoe-/**/
        //Row Deliminator Deliminatoe-/***/
        //table deliminator -/****/
    }

To convert into JSON
    public string DataTableToJson(DataTable table)
    {
        var lst = new List<Dictionary<string, object>>();
        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();
            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = row[col];
            }
            lst.Add(dict);
        }
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Serialize(lst);
    }

To run the program , we have to add the namespace
//add this Namespace
using System.Text;
using System.Data;

Now I am creating a data table
//define a data table
        DataTable dt = new DataTable();
        dt.Columns.Add("col1", typeof(String));
        dt.Columns.Add("col2", typeof(String));
        dt.Columns.Add("col3", typeof(Double));

I am adding some data to it
DataRow dr = dt.NewRow();
        dr["col1"] = "abc1";
        dr["col2"] = "efg1";
        dr["col3"] = "100";
        dt.Rows.Add(dr);


        //adding row to data table
        DataRow dr1 = dt.NewRow();
        dr1["col1"] = "abc2";
        dr1["col2"] = "efg2";
        dr1["col3"] = "200";
        dt.Rows.Add(dr1);

Now I am calling function to convert data table to string
string strdata = DataTable2String(dt);
output :abc1/**/efg1/**/100/**//***/abc2/**/efg2/**/200/**//***//****/

Now I am calling function to convert data table to Json
string strdata = DataTableToJson(dt);
//output : [{"col1":"abc1","col2":"efg1","col3":100},{"col1":"abc2","col2":"efg2","col3":200}]

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...