dataSet转string 实际上是转xml格式的字符串
string转dataset 是xml格式转DataSet
DataTable转string 是先把DataTable添加到DataSet 然后再转string
以下是核心代码
/// <summary> /// 代码生成一个DataTable /// </summary> /// <returns></returns> private DataTable testDataTable() { DataTable tblDatas = new DataTable("Datas"); DataColumn dc = null; dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); dc.AutoIncrement = true;//自动增加 dc.AutoIncrementSeed = 1;//起始为1 dc.AutoIncrementStep = 1;//步长为1 dc.AllowDBNull = false;// dc = tblDatas.Columns.Add("Product", Type.GetType("System.String")); dc = tblDatas.Columns.Add("Version", Type.GetType("System.String")); dc = tblDatas.Columns.Add("Description", Type.GetType("System.String")); DataRow newRow; newRow = tblDatas.NewRow(); newRow["Product"] = "大话西游"; newRow["Version"] = "2.0"; newRow["Description"] = "我很喜欢"; tblDatas.Rows.Add(newRow); newRow = tblDatas.NewRow(); newRow["Product"] = "梦幻西游"; newRow["Version"] = "3.0"; newRow["Description"] = "比大话更幼稚"; tblDatas.Rows.Add(newRow); return tblDatas; } /// <summary> /// DataSet转string /// </summary> /// <param name="ds"></param> /// <returns></returns> private string DataSetToString(DataSet ds) { return ds.GetXml(); } /// <summary> /// String转DataSet /// </summary> /// <param name="str"></param> /// <returns></returns> private DataSet StringToDataSet(string str) { DataSet ds = null; try { StringReader sr = new StringReader(str); ds = new DataSet(); ds.ReadXml(sr); return ds; } catch (Exception ex) { } return ds; }
以下是方法调用
private void button1_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataTable dt = testDataTable();//得到一个DataTable ds.Tables.Add(dt);//将dataTable添加到dataSet里面 string s = DataSetToString(ds);//DataSet转string DataSet ds2 = StringToDataSet(s);//String转DataSet }