简体   繁体   中英

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

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() + "}";
}

为什么不使用row.Table.Columns属性而不是反射?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM