Reputation: 1637
I have a model class as below.
public class EmployeeModel
{
public string Name { get; set; }
public int Age { get; set; }
public double Salary { get; set; }
}
I want its fields and values to be mapped to a WinForm DataGridView as shown below.
I adopted reflection strategy to do this like below.
EmployeeModel emp = new EmployeeModel();
emp.Name = "Dev";
emp.Age = 25;
emp.Salary = 150000;
PropertyInfo[] props = typeof(EmployeeModel).GetProperties();
foreach (PropertyInfo prop in props)
{
object val = prop.GetValue(emp, null);
dataGridView1.Rows.Add(prop.Name, val);
}
Now I may need to loop the columns and do some reflection to convert these values to an EmployeeModel object. It feels to me that I am on the wrong track.
I have two questions.
Upvotes: 0
Views: 614
Reputation: 32445
Use PropertyGrid
for this purpose:
EmployeeModel emp = new EmployeeModel();
emp.Name = "Dev";
emp.Age = 25;
emp.Salary = 150000;
If you will add PropertyGrid
to your form through designer,
then just set a your object to SelectedObject
and control will handle the rest
this.MyPropertygrid.Text = "Employee";
this.MyPropertyGrid.SelectedObject = emp;
Upvotes: 2