Я пытаюсь получить идентификатор id
каждого элемента в классе
но вместо этого он оповещает каждое имя класса отдельно, поэтому для class = " У меня есть DataGridView на форме, и он называется DataGridView1. У меня есть CSV только с 3 столбцами данных, и я хочу иметь возможность отображать их.
Рассмотрим этот фрагмент кода. Измените по своему усмотрению или в соответствии с вашими требованиями. Вам потребуются операторы Imports
для System.IO
и System.Data.OleDb
.
Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
Dim conn As New OleDbConnection(connectionString)
conn.Open()
'the SELECT statement is important here,
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)
Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect
Dim ds As New DataSet
adapter1.Fill(ds, "DATA")
myDataGridView.DataSource = ds.Tables(0).DefaultView
myDataGridView.DataBind
conn.Close()
Используйте класс TextFieldParser, встроенный в .Net framework.
Вот код, скопированный из сообщения на форуме MSDN Пола Клемента. Он преобразует CSV в новую DataTable в памяти, а затем привязывает DataGridView к DataTable
Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
Next
End If
Row = TextFileTable.NewRow
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
End If
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
TextFileReader.Dispose()
frmMain.DataGrid1.DataSource = TextFileTable
Рассмотрим эту статью / проект CodeProject: LINQ TO CSV .
Это позволит вам создать собственный класс, по форме напоминающий столбцы вашего файла .csv. Затем вы использовали CSV и привязывались к своему DataGridView.
Dim cc As new CsvContext()
Dim inputFileDescription As New CsvFileDescription() With { _
.SeparatorChar = ","C, _
.FirstLineHasColumnNames = True _
}
Dim products As IEnumerable(Of Product) = _
cc.Read(Of Product)("products.csv", inputFileDescription)
' query from CSV, load into a new class of your own
Dim productsByName = From p In products
Select New CustomDisplayClass With _
{.Name = p.Name, .SomeDate = p.SomeDate, .Price = p.Price}, _
Order By p.Name
myDataGridView1.DataSource = products
myDataGridView1.DataBind()