vinayan
vinayan

Reputation: 1637

Bind a single Object's Fields and Values to a two column datagrid vertically Winform

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.

enter image description here

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.

  1. What would be the best way to bind a class object to a DataGridView in this way?
  2. Suppose my class contains a field(Example, Grade(integer)). This field value needs to be populated as a combobox inside the datagrid with values such as "Manager,Developer,CEO" etc. What would be be needed to do in that case?

Upvotes: 0

Views: 614

Answers (1)

Fabio
Fabio

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

Related Questions