I have job class numbers stored on the database and want to show my data in "DataGridView" by replacing the job class numbers with job class name.
I use Entity Framework and retrieve data from the database to a generic list.
I try to create DataTable and bound the DataGridView to it.
Is this way correct?
In my code below I want to determine the column that is used in DataTable but it does not work properly if I remove column names ("ID", "Nme", "jobClass" ... ) it work and show all columns in DataGridView but with add column names I get reeor.
`
IEnumerable<Employee> employeesList = new List<Employee>();
employeesList = db.EmployeeRepository.GetAllEmployees();
DataTable employeesTable = new DataTable();
using (var reader = ObjectReader.Create(employeesList,"ID", "Name", "jobClass", "College", "Department" ))
{
employeesTable.Load(reader);
}
dgvEmployees.DataSource = employeesTable;
`
CodePudding user response:
One way to do it is using Json to do the conversions.
You will convert your main object to Json and then convert it into a DataTable:
string data = JsonConvert.SerializeObject(employeesList);
employeesTable = JsonConvert.DeserializeObject<DataTable>(data);
To define the fields you want in the DataTable, in your "Employee" object, mark the fields you don't want in the DataTable with the attribute "[JsonIgnore()]", as in the example below:
public class Employee
{
[JsonIgnore()]
public string ID { get; set; }
public string Name { get; set; }
public string jobClass { get; set; }
public string College { get; set; }
public string Department { get; set; }
}
CodePudding user response:
I use partial class to change my data model and solve my problem. see this link and this