No, You can't return a DataTable object from a webservice method.
If you try, ends up with the following message
"System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: Cannot serialize the DataTable. DataTable name is not set. at System.Data.DataTable.WriteXmlSchema(XmlWriter writer, Boolean writeHierarchy)
at System.Data.DataTable.System.Xml.Serialization.IXmlSerializable.WriteXml(XmlWriter writer)
at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_DataTable(Object o)
at Microsoft.Xml.Serialization.GeneratedAssembly.DataTableSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
at System.Web.Services.Protocols.WebServiceHandler.Invoke()"
If you look into the message, we can find that DataTable is not serializable. Or in other words, since DataTable doesn't implement the ISerializable interface.
It can't be used as a return type for a webserivice method.
Alternatively, create you own class which inherits ISerializable interface. And pass the data using that newly created object. Or create the data in XML format
and pass it as a string.
Try out below code ,
Web service:
[WebMethod]
public DataTable HelloWorldDataSet()
{
DataTable dt = new DataTable("MyDataTable");
dt.Columns.Add("column1",typeof(System.String));
dt.Columns.Add("column2", typeof(System.String));
DataRow dr = dt.NewRow();
dr["column1"] = "Your Data";
dr["column2"] = "Your Data";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["column1"] = "Your Data";
dr["column2"] = "Your Data";
dt.Rows.Add(dr);
return dt;
}
Client code:
private void button1_Click(object sender, EventArgs e)
{
helloservice.Service1 service = new WindowsFormsApplication1.helloservice.Service1();
DataTable dt = service.HelloWorldDataSet();
}
Or you can return Dataset instead of dataTable refer this link
[
^]
I Hope it will help you,Enjoy....