I have mapped my models and come up with the following code below. How to display the data as well the column names using datagridview?
public class DivisionModel
{
public int id { get; set; }
public string DivisionName { get; set; }
}
public class EmployeeModel
{
public int id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DivisionModel Division { get; set; }
}
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db)))
{
var sql = @"SELECT * FROM[Employee] em JOIN Division dv ON em.DivisionId = dv.id";
var result = connection.Query<EmployeeModel, DivisionModel, EmployeeModel>(sql, (employee, division) => { employee.Division = division; return employee; });
result.ToList().ForEach(employee => MessageBox.Show(($"FirstName: {employee.FirstName},MiddleName: {employee.MiddleName}, LastName: {employee.LastName},Division: {employee.Division.DivisionName}")));
}
Usually, simply assigning the list as the data source should be sufficient, ie
var data = result.ToList();
// TODO: any debug code you want to inspect "data" here, as per your MessageBox.Show
yourGrid.DataSource = data;
Note: if you have a BindingSource
configured against the DataGridView
, then you'd update the BindingSource
's DataSource
instead.
Make a datatable and then make the datagridview1.DataSource = dt;
public class EmployeeModel
{
public int id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DivisionModel Division { get; set; }
public DataTable MakeTable(List<EmployeeModel> model)
{
DataTable dt = new DataTable();
dt.Columns.Add("Employee Id", typeof(int));
dt.Columns.Add("First Name", typeof(string));
dt.Columns.Add("Middle Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
dt.Columns.Add("Division Id", typeof(int));
dt.Columns.Add("Division Name", typeof(string));
foreach(EmployeeModel employee in model)
{
dt.Rows.Add(new object[] { employee.id, employee.FirstName, employee.MiddleName, employee.LastName, employee.Division.id, employee.Division.DivisionName });
}
return dt;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.