2017-03-06 99 views
0

如何篩選數據表如下?如何篩選數據表

我有兩個數據表作爲[cancelledOrders]和[allOrders] n我的vb.net表單中都有一個列名[OrderNo]。

我想要做的是過濾[allOrders]數據表,其中[OrderNo]列不包含等於[cancelledOrders]的[OrderNo]列中的值的任何值。

我試圖使用字符串列表。但我沒有成功。請有人幫助我。

感謝

回答

0

你的問題不明確,如果你需要一個展覽過濾器或數據取過濾器,所以我會承擔後者。我會假設你的[OrderNo]列是Integer。所以,在這裏你去:

Function FilterCancelledOrders(allOrders As DataTable, cancelledOrders As DataTable) As DataRow 

    ' Let's use LInQ to collect all the numbers of cancelledOrders into an Array Of Integer 
    Dim CancelledOrderNos = cancelledOrders.Select.Select(
     Function(dr) dr.Field(Of Integer)("OrderNo")).ToArray 

    ' Now let's collect all dataRows from allOrders where OrderNo is contained in the Array of Integer we just got above: 
    Dim CancelledOrderRows = allOrders.Select.Where(
     Function(dr) CancelledOrderNos.Contains(dr.Field(Of Integer)("OrderNo"))).ToArray 

    ' If this is enough for your needs, now you have an Array of DataRow containing 
    ' all rows in [allOrders] whose [OrderNo] field info is contained in the corresponding 
    ' field of any row in [cancelledOrders] 
    Return CancelledOrderRows 
End Function 

編輯:這個版本隱藏未選中的行:

Sub FilterCancelledOrders(allOrdersView As DataGridView, cancelledOrders As DataTable, dgview as DataGridView) 

    ' so far, same as before, but type String 
    Dim CancelledOrderNos = cancelledOrders.Select.Select(
     Function(dr) dr.Field(Of String)("OrderNo")).ToArray 

    ' iterate through DataGridView's rows 
    For each dgvr as DataGridViewRow in dgview.Rows 

     ' set row visibility according to your criterium 
     dgvr.Visible = Not CancelledOrderNos.Contains(dgvr.Cells("OrderNo").Value) 

    Next 

    ' it's done! 

End Sub 

否則後果自負您可以創建一個過濾的數據表,並將其設爲您的DataGridView的數據源:

Function GetPositiveOrdersDataTable(allOrders As DataTable, cancelledOrders As DataTable) As DataTable 

    Dim CancelledOrderNos = cancelledOrders.Select.Select(
     Function(dr) dr.Field(Of Integer)("OrderNo")).ToArray 

    ' Collect all dataRows from allOrders where OrderNo is NOT contained in the Array of Integer we just got above: 
    Dim positiveOrderRows = allOrders.Select.Where(
     Function(dr) Not CancelledOrderNos.Contains(dr.Field(Of Integer)("OrderNo"))).ToArray 

    ' create empty table with same structure as allOrders 
    Dim positiveOrders = allOrders.Clone() 

    ' populate it with orders that were not cancelled 
    For each dr in positiveOrderRows 
     positiveOrders.ImportRow(dr) 
    Next 

    Return positiveOrders 
End Function 
+0

首先感謝您對您的支出寶貴的時間。實際上,它們在運行時用於填充datagridview。我有一些複選框使用DataView.RowFilter過濾數據表。所以我想我需要一個展覽過濾器。對不起,我不能提到[OrderNo]列都是字符串。讓我試着用你的答案編碼:) –

+0

請參閱編輯。 – VBobCat

+0

非常感謝你@VBobCat。在你的幫助下,我可以繼續。再次感謝 –

1

我會在SQL查詢中過濾。它會是這個樣子:

SELECT allOrders * FROM allOrders WHERE NOT EXISTS(SELECT * FROM cancelledOrders WHERE cancelledOrders.orderno = allOrders.orderno)