C# Reflection: Getting the fields of a DataRow fro

2019-05-22 16:39发布

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

1条回答
在下西门庆
2楼-- · 2019-05-22 16:44

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

查看更多
登录 后发表回答