C#-WebService Soap Exception

I am trying to retrieve a list of dropdown items from the database. The code works good if I am not using a Web Service to access the database, but when I used webservice to access the database, it gives me a Soap Exception. Here is the code, please help.

The Exception is:

System.Web.Services.Protocols.SoapException: Server was unable to process request. --->
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)

Here is the Method:

private void retrieveStates()
        {
            dataService = new PCDDA.Service();
            DataTable dt = new PCDDA.Service().GetStates();
            DDLSelectState.DataSource = dt;
            DDLSelectState.DataTextField = "RegionName";
            DDLSelectState.DataValueField = "RegionID";
            DDLSelectState.DataBind();
            DDLSelectState.Items.Insert(0, new ListItem("<Select State>", "0"));
        }

Here is the GetStates() Web Method which is in the Service.cs class of the Web Service:

[WebMethod]
    public DataTable GetStates()
    {
        DbPostcardOTR db = new DbPostcardOTR();
        try
        {
            DataTable loadstates = db.LoadStates();
            return loadstates;

        }
        catch (Exception ex)
        {
            throw new Exception("Unable to retrieve or load States from the database. The Exception is :" + ex.Message);
        }

    }

This is the LoadStates() Method in the DbPostcardOTR.cs:

 public DataTable LoadStates()
    {
        DataTable States = new DataTable();
        SqlConnection con = OpenConnection();
        try
        {
            string selectSQL = "Select RegionID, RegionName from PCDDev.dbo.tblDistributionArea";
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader dr = cmd.ExecuteReader();
            States.Load(dr);
            return States;
        }
        finally
        {
            if (con != null)
                con.Close();
        }
    }

Upvotes: 0

Views: 5146

Answers (1)

Jeremy
Jeremy

Reputation: 9010

From Microsoft:

The DataTable, DataRow, DataView, and DataViewManager objects cannot be serialized and cannot be returned from an XML Web service. To return less than a complete DataSet, you must copy the data that you want to return to a new DataSet.

Source: Problems using an XML Web service that returns a DataTable

Note: The above source contains an alternative which may work in your situation. In a nutshell, return a DataSet.

Upvotes: 1

Related Questions