使用条件DGV VB.NET显示SQL结果

时间:2012-06-10 17:51:21

标签: sql vb.net winforms datagridview filter

我的问题在于将值显示到DGV控件的单元格中,例如:

MySQL表:

ID - Name      - Price    - Type
1    Mouse Pad   2.85$    -  a
2    Keyboard    10.50$   -  a
3    Hard Disk   80.00$   -  c
4    Web Cam     15.02$   -  b
5    Printer     45.62$   -  c
6    DVD Writer  20.00$   -  b

我的DataGridView控件:

ID - Name       - PriceA    - PriceB    - PriceC

我希望显示结果使用这些条件过滤[VB.NET sintax]:

If SQLcolumn(Type) = a Then, show the price into PriceA into the DGV.
If SQLcolumn(Type) = b Then, show the price into PriceB into the DGV.
If SQLcolumn(Type) = c Then, show the price into PriceC into the DGV.

2 个答案:

答案 0 :(得分:1)

一种方法是创建一个包含5列的自定义列表:ID,Name,PriceA,PriceB,PriceC 例如,从数据库获取数据并将数据填充到数据表后,您可以逐行处理数据表,并检查数据表行的Type列是否为Type'a',然后将行添加到List中并将Price添加到列表的PriceA列,在处理整个数据表并将其所有行添加到List后,可以将List设置为Datagridview数据源!

答案 1 :(得分:1)

您可以使用SQL Pivot运算符执行此操作:

SELECT  ID ,
        Name ,
        [a] AS [TypeA] ,
        [b] AS [TypeB] ,
        [c] AS [TypeC]
FROM    tbl PIVOT ( SUM(Price) FOR TYPE IN ( a, b, c ) ) AS pvt