Search code examples
c#sql-serverdapper

Dapper query result to datagridview


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}")));
}

Solution

  • 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;
        }
    }