开发者

How to dynamically assign a property in a collection

I work on C#.

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (Convert.ToBoolean( item.Cells[0].Value) == true)
    {
        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            **class oclass=new class();
            oclass.property = item.Cells[col.Name].Value.ToString();
            Collection.add(oclass);**
        }
    }

}

In the above syntax,i want to fill class property dynamically.I also add my class in collection.Is it possible in C#,fill class property dynamically?My grid contain more than one column.My grid's column n开发者_如何学Came are same as class property name.I want to do the bellow thing:

foreach (DataGridViewColumn col in dataGridView1.Columns)
{
    **class oclass=new class();
    oclass.col.Name= item.Cells[col.Name].Value.ToString();
    Collection.add(oclass);**
}

Thanks in advance.


You can do this with PropertyInfo.SetValue().

Within the example, I've added an explanation of what it all does.

I've used the class TestClass for this example. First I get the type.

var type = typeof(TestClass);

Then, I build a dictionary of all column names and a PropertyInfo which is a reference to the property of the class with the same name as the column.

var properties = new Dictionary<string, PropertyInfo>();

foreach (DataGridViewColumn col in dataGridView1.Columns)
{
    properties.Add(col.Name, type.GetProperty(col.Name));
}

Then, for each row.

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (Convert.ToBoolean( item.Cells[0].Value) == true)
    {

I create a new instance of TestClass.

        var instance = new TestClass();

        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {

I take the property from the dictionary and use the method SetValue to set the value of the instance with the value from the column. But, to be able to do this, we must first ensure that the type is correct.

            object value = Convert.ChangeType(item.Cells[col.Name].Value, properties[col.Name].PropertyType);

            properties[col.Name].SetValue(instance, value, null);
        }

And last, I add the instance to the collection.

        Collection.Add(instance);
    }
}


i miss the sense of your question, what do you want to achieve with the second snippet ? Btw yes, you can set the value of a class member(property) at runtime if that property is already defined in the class. Alternatives are to derive a new class from the parent one and add the missing members or if you want something more dynamic well use the dynamic type introduced with .Net 4.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜