简体   繁体   English

Dapper 查询结果到 datagridview

[英]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?如何使用 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.注意:如果您针对DataGridView配置了BindingSource ,那么您将改为更新BindingSourceDataSource

Make a datatable and then make the datagridview1.DataSource = dt;制作一个数据表,然后制作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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM