Sub FillListview_by_datatable(ByVal lvw As ListView,ByVal dt As DataTable) lvw.Clear For Each col As DataColumn In dt.Columns lvw.Columns.Add(col.ColumnName) Next For i = 0 to dt.Rows.Count -1 Dim lvwitem As ListViewItem = lvw.Items.Add(dt.Rows(i)(0)) For j = 1 to dt.Columns.Count -1 lvwitem.SubItems.Add(dt.Rows(i)(j).ToString) Next Next End Sub
Tuesday, 26 June 2012
Fill listview by datatable
Fill listview by linq result
Here is how to fill listview (winform) (vb.net) from any linq result without the need to knowing
the fields name or count, just pass query_result.ToArray to the function
Enjoy!!
Dim db As New northwindDataContext Dim query = From t In db.Customers Select t FillListview_by_Linqresult(query.ToArray,lvwListView1)
Sub FillListview_by_Linqresult (ByVal linq_result As Array,ByVal lvw As ListView) Dim col_count = linq_result(0).GetType.GetProperties().Count ' Add listview headers For i = 0 to col_count -1 Dim col_name = linq_result(0).GetType.GetProperties()(i).Name.ToString lvw.Columns.Add(col_name) Next i ' Fill listview with values For i = 0 to linq_result.Length - 1 Dim lvwitem as ListViewItem = lvw.Items.Add(linq_result(i).GetType.GetProperties()(0).GetValue(linq_result(i),Nothing)) For j = 1 to col_count -1 Dim sub_item = linq_result(i).GetType.GetProperties()(j).GetValue(linq_result(i),Nothing) If sub_item is Nothing then sub_item = "" sub_item = sub_item.ToString.Trim lvwitem.SubItems.Add(sub_item) Next j Next i End Sub
Subscribe to:
Posts (Atom)