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 name 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
TestClassfor this example. First I get the type.Then, I build a dictionary of all column names and a
PropertyInfowhich is a reference to the property of the class with the same name as the column.Then, for each row.
I create a new instance of
TestClass.I take the property from the dictionary and use the method
SetValueto 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.And last, I add the instance to the collection.