2011-06-30 34 views
1

說我有三個包含多個對象的列表。讓我們也假設他們每個都包含相同數量的項目。例如有沒有辦法從多個列表中填充dataGridView而不遍歷列表?

Dim mylist1 as List(Of Integer) 
Dim myList2 as List(Of Integer) 
Dim myList3 as List(Of Integer) 
... 
... <lists are populated here with say 10 items each 
... 

現在說我有一個datagridview,我已經定義爲有三列。是否有辦法將每個列表的內容分配給三列中的每一列(例如列1 = myList1,列2 = myList2等),而不遍歷每個列表?我知道我可以定義一個dataTable,創建列,並遍歷每個列表...然後將dataTable關聯到dataGridView的dataSource。但是,我不想遍歷列表,因爲在我的真實應用程序中,這些列表很大,並且迭代需要很長時間。我只是想知道如何將這些列表批量分配給dataTable中的列。有沒有辦法做到這一點?

+0

我想我知道如何使用DataSource屬性將dataTable綁定到dataGridView。但是,問題是,如何將三個列表加載到dataTable的每一列? – GregH

回答

0

如果您使用的是.NET 4.0,則可以使用.Zip擴展方法IEnumerable<T>將三個列表關聯在一起。

C#

var output 
    = list1.Zip(list2, (a, b) => new { a, b }) 
      .Zip(list3, (x, c) => new { First = x.a, Second = x.b, Third = c }); 

VB

Dim output 
    = list1.Zip(list2, function (a, b) new With { .a = a, .b = b }) _ 
      .Zip(list3, function (x, c) new with { .First = x.a, .Second = x.b, .Third = c }) 

這將導致在一個序列中的匿名類型對象,具有屬性First, Second, Third。列表的迭代將被推遲到需要的時候,這將在您將數據綁定到您的控件的位置。

+0

對不起,使用3.5 – GregH

1

使用虛擬模式。

Public Class Form1 
    Private mlst1 As New List(Of Integer) 
    Private mlst2 As New List(Of Integer) 
    Private mlst3 As New List(Of Integer) 


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    mlst1.Add(1) 
    mlst1.Add(2) 
    mlst1.Add(3) 

    mlst2.Add(4) 
    mlst2.Add(5) 
    mlst2.Add(6) 

    mlst3.Add(7) 
    mlst3.Add(8) 
    mlst3.Add(9) 

    DataGridView1.VirtualMode = True 
    DataGridView1.Columns.Add("A", "A") 
    DataGridView1.Columns.Add("B", "B") 
    DataGridView1.Columns.Add("C", "C") 
    DataGridView1.Rows.Add() 
    DataGridView1.Rows.Add() 
    DataGridView1.Rows.Add() 
    End Sub 


    Private Sub DataGridView1_CellValueNeeded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValueNeeded 
    Select Case e.ColumnIndex 
     Case 0 
     e.Value = mlst1(e.RowIndex) 
     Case 1 
     e.Value = mlst2(e.RowIndex) 
     Case 2 
     e.Value = mlst3(e.RowIndex) 
     Case Else 
     e.Value = "" 
    End Select 
    End Sub 
End Class 
+0

這似乎非常複雜,因爲似乎_CellValueNeeded事件不是唯一需要處理的事件。我正在做一些研究,並且有一系列事件需要檢查。另外,當只使用_CellValueNeeded時,我得到一個錯誤,說我需要使用「WithEvents」修飾符來添加gridView。試過這樣做,但無法讓它工作。令人驚訝的是沒有簡單的方法來簡單地獲取列表並將其綁定到dataTable或dataGridView中的列。 – GregH