C# Reflection: Getting the fields of a DataRow from a Typed DataSet

Andreas Grech picture Andreas Grech · Jan 10, 2009 · Viewed 12.1k times · Source

I am currently building a method that takes an object that is of type DataRow from a typed DataSet, and then returning a string in JSON format of the fields in the DataRow (for use in a Web Service).

By using System.Reflection, I am doing something like this :

public string getJson(DataRow r)
    {
        Type controlType = r.GetType();
        PropertyInfo[] props = controlType.GetProperties();
        foreach (PropertyInfo controlProperty in props)
        {

        }
        return "";
    }

And then in the foreach statement, I would iterate every field and get the field name and value, and format it into JSON.


The problem is that when iterating over the props (of type PropertyInfo[]), I am getting properties that I do not want to be iterated over:

alt text http://img88.imageshack.us/img88/2001/datarowreflectionht0.gif

As you can see from the above image, I only need the fields that range from 0 - 11 in the props array, because those are the 'real fields' of this particular typed row.

So my question is, How can I get the fields of the Typed DataRow only, and not the other 'metadata' ?


[UPDATE with Solution]

As Mehrdad Afshari suggested, instead of using Reflection, I am using the Table.Columns array.

Here is the completed function:

public string GetJson(DataRow r)
{
    int index = 0;
    StringBuilder json = new StringBuilder();
    foreach (DataColumn item in r.Table.Columns)
    {
        json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString()));
        if (index < r.Table.Columns.Count - 1)
        {
            json.Append(", ");
        }
        index++;
    }
    return "{" + json.ToString() + "}";
}

Answer

mmx picture mmx · Jan 10, 2009

Why don't you use row.Table.Columns property instead of reflection?