以下三种方案的实质应该都是序列化的,有一位大神说过“跨进程的不序列化应该去面壁!”O(∩_∩)O哈哈哈~
解决方案一:返回dataset
WebService中的方法代码如下:
[WebMethod]
public DataSet GetDataSet()
{
DataTable dt=new DataTable("mytable");
DataColumn dc=new DataColumn("id",typeof(string));
dt.Columns.Add(dc);
DataRow dr=dt.NewRow();
dr["id"]="1111111";
dt.Rows.Add(dr);
DataSet ds=new DataSet();
ds.Tables.Add(dt);
return ds;
}
在调用客户端直接使用DataSet
DataSet ds = db.GetDataSet();//db是服务代理类实例
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
解决方案二:给返回的datatable命名
webservice文件中
[WebMethod]
public DataTable dt()
{
DataTable dt = new DataTable("default");
dt.Columns.Add("id");
dt.Columns.Add("name");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr["id"] = i.ToString();
dr["name"] = "name" + i.ToString();
dt.Rows.Add(dr);
}
return dt;
}
调用页面中
WebService1.WebService1 service = new WebService1.WebService1();
DataTable dt = service.dt();
gvUser.DataSource = dt;
gvUser.DataBind();
最关键的是在webservice的方法中为datatable命名,否则就会报错.
解决方案三:服务中将DataTable的序列化成xml字符串,调用时候在反序列化成DataTable
#region DataTable序列化和反序列化 /// <summary> /// DataTableToXML /// </summary> public static string ConvertDataTableToXML(DataTable dt) { return ConvertDataTableToXML(dt, string.Empty); } public static string ConvertDataTableToXML(DataTable dt, string aaa) { StringWriter sw = null; try { if (dt.TableName == string.Empty) dt.TableName = "table1"; sw = new StringWriter(); dt.WriteXml(sw, XmlWriteMode.WriteSchema); return sw.ToString(); } catch (System.Exception ex) { throw ex; } finally { if (sw != null) sw.Close(); } } /// <summary> /// XMLToDataTable /// </summary> public static DataTable ConvertXMLToDataTable(string xmlData) { TextReader sr = null; try { DataTable dt = new DataTable(); sr = new StringReader(xmlData); dt.ReadXml(sr); return dt; } catch (System.Exception ex) { throw ex; } finally { if (sr != null) sr.Close(); } } #endregion