vb.net 如何在具有某些列和行的 Datagridview 中导入 csv 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19508596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import csv file in Datagridview with certain columns and rows?
提问by noahtot
I'm new to VB.net and I don't know how to display certain columns and rows in datagridview that was imported from CSV file. My problem is I have many columns and all I want to display is 2 columns:
我是 VB.net 的新手,我不知道如何在从 CSV 文件导入的 datagridview 中显示某些列和行。我的问题是我有很多列,而我只想显示 2 列:
Name,Age,Mobile Number,ID number
姓名、年龄、手机号码、身号码
Alex,18,09848484841,0010
亚历克斯,18,09848484841,0010
George,19,02987654321,0020
乔治,19,02987654321,0020
Toni,17,09277470257,0030
托尼,17,09277470257,0030
How can I display only the Name & Age columns and its rows?
如何仅显示名称和年龄列及其行?
回答by tinstaafl
If you use a datatable you get the data structure and collection together. something like this:
如果您使用数据表,您将获得数据结构和集合。像这样:
Dim sr As New IO.StreamReader(filename)
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(","c)
dt.Columns.AddRange({New DataColumn(newline(0)), _
New DataColumn(newline(1))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}
dt.Rows.Add(newrow)
End While
DataGridView1.DataSource = dt
回答by OneFineDay
Use a custom class with properties that match the data you want to store and make an instance of that class for each row of data use read, then have a List(Of {custom class})to hold each object and the DGV's DataSourceproperty can view the collection in the grid. The property names in the class will be used as the header.
使用具有与您要存储的数据匹配的属性的自定义类,并为每行数据使用读取该类的实例,然后有一个List(Of {custom class})来保存每个对象,DGV 的DataSource属性可以查看网格中的集合。类中的属性名称将用作标题。

