将SQL查询中的信息放入DataGridView中

时间:2014-03-01 23:18:35

标签: c# sql oracle datagridview

显示此SQL语句结果的最佳方法是什么:

select "WorkOrder"."WorkOrderID", "Customer"."FirstName", "Vehicles"."Model", "WorkOrder"."State" 
from "WorkOrder", "Customer", "Vehicles"
WHERE "WorkOrder"."VIN" = "Vehicles"."VIN" 
  AND "Vehicles"."CustomerID" = "Customer"."CustomerID"
  AND "WorkOrder"."State" = 'In Progress';

我在Visual Studio 2010中使用C#WinForms。我似乎无法弄清楚如何将它放在DataGridView或类似的东西中。有什么方法可以做或者把它骗到DataGridView吗?

1 个答案:

答案 0 :(得分:0)

将最简单的方法放入DataTable并将其分配给.DataSource属性,例如;

string command = @"select "WorkOrder"."WorkOrderID", "Customer"."FirstName", "Vehicles"."Model", "WorkOrder"."State"  from "WorkOrder", "Customer", "Vehicles" WHERE "WorkOrder"."VIN" = "Vehicles"."VIN" AND "Vehicles"."CustomerID" = "Customer"."CustomerID" AND "WorkOrder"."State" = 'In Progress'";

using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand command = conn.CreateCommand())
{
    command.Connection = conn;
    using(SqlDataAdapter adapter = new SqlDataAdapter())
    {
        adapter.SelectCommand = command;
        DataTable table = new DataTable();
        adapter.Fill(table);
        DataGridview1.DataSource = table;
        DataGridview1.AutoGenerateColumns = true;
    }
}