以下代码将我的CSV文件导入数据网格。唯一的问题是它使用CSV文件中的一行填充标题,我希望标题留空并在其后导入行。请指教。
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim fi As New FileInfo(OpenFileDialog1.FileName)
Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
Dim objConn As New OleDbConnection(sConnectionStringz)
objConn.Open()
'DataGridView1.TabIndex = 1
Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
Dim objAdapter1 As New OleDbDataAdapter
objAdapter1.SelectCommand = objCmdSelect
Dim objDataset1 As New DataSet
objAdapter1.Fill(objDataset1, "test")
'--objAdapter1.Update(objDataset1) '--updating
DataGridView1.DataSource = objDataset1.Tables(0).DefaultView
objConn.Close()
End If
答案 0 :(得分:0)
我想到了两个想法,只需在 grid_ColumnAdded事件处理程序
中添加列时删除标题单元格 if e.Column.HeaderText = "YourColumnHeaderText" Then
e.Column.HeaderText = String.Empty;
或者使用streamreader读取CSV文件可能更容易,参考:http://www.dotneter.com/import-csv-file-into-datagridview(注意我会加载到Datatable而不是直接填充Grid):
Dim streamReader As System.IO.StreamReader = New StreamReader(txtPath.Text)
'Reading CSV file header
rowValue = streamReader.ReadLine()
cellValue = rowValue.Split(","C)
Dim i As Integer = 0
While i <= cellValue.Count() - 1
Dim column As New DataGridViewTextBoxColumn()
column.Name = cellValue(i)
column.HeaderText = cellValue(i)
dataGridView1.Columns.Add(column)
i += 1
End While
'Reading CSV file content
While streamReader.Peek() <> -1
rowValue = streamReader.ReadLine()
cellValue = rowValue.Split(","C)
dataGridView1.Rows.Add(cellValue)
End While
最后一个想法是在分配给Grids数据源之前从数据表中删除一行:http://msdn.microsoft.com/en-us/library/feh3ed13(v=vs.80).aspx
objDataset1.Tables(0).Rows [0] .Delete();