Saturday, September 20, 2008

Object Array to DataSet

I’m working with a Web Service right now that returns an array of objects. What I want to do, is bind the Object Array to a DataGrid. I was able to convert the Object Array to a DataSet and then bind it to the DataGrid.

Code Snippet

using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;


namespace BusinessObject.Util
{
///
/// Utility Class for Object Arrays.
///

public class ObjectArray
{
private Object[] _objectArray;

public ObjectArray(Object[] objectArray)
{
this._objectArray = objectArray;
}

public DataSet ToDataSet()
{
DataSet ds = new DataSet();

XmlSerializer xmlSerializer =
new XmlSerializer(_objectArray.GetType());
StringWriter writer = new StringWriter();
xmlSerializer.Serialize(writer, _objectArray);
StringReader reader =
new StringReader(writer.ToString());

ds.ReadXml(reader);
return ds;
}
}
}

How to Use the ObjectArray Class with a Web Service

I would think that it’s obvious how this class should be used, but there’s always a chance that the person reading this article is new to .NET and could use an explanation.

Save the class to a folder in your project and change the Namespace of the class to match the location in your project.

Let’s say that the Web Service provided you with an array of “Persons” ( Person [ ] ). Create a new Person Array:

Person[] personList;

Call the Web Service method that returns the Person Array:

personList = Course.GetPersonList();

Instantiate the downloaded “Object Array” class with the personList:

ObjectArray objectArray = new ObjectArray(personList);

Create a DataSet and convert your ObjectArray to a DataSet using the method:

DataSet ds = new DataSet();
ds = objectArray.ToDataSet();

No comments: