【发布时间】:2016-07-20 11:24:50
【问题描述】:
我有一个 .csv 文件,我将其加载到数据网格视图内的组合框中。我的 csv 是这样的:
prodname,prodcode,amt
prodname1,prodcode1,amt1
prodname2,prodcode2,amt2
prodname 是我在 datagridview 内的组合框中显示的内容。
我想要的是当我选择prodname1、prodcode1 和amt1 时将显示在数据网格视图的同一行上。我刚刚开始在 vb.net 中摸索,如果有人帮助我,我将不胜感激。
这是我现在拥有的:
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "Product Name"
cmb.Name = "cmb"
DataGridView2.Columns.Add(cmb) 'code for a combobox column in datagridview
Dim filename As String
Dim dt As New DataTable
filename = "/file/path/here"
Dim sr As New IO.StreamReader(filename)
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(",")
Dim newrow As DataRow = dt.NewRow
cmb.Items.Add(newline(0))
newrow.ItemArray = {newline(1)}
dt.Rows.Add(newrow)
End While
DataGridView2.DataSource = dt
更新:
我根据 Alex 的回答更新了我的代码,但仍然出现错误。
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "Product Name"
cmb.Name = "cmb"
DataGridView1.Columns.Add(cmb)
AddHandler DataGridView1.CellValueChanged, AddressOf DataGridView1_OnCellValueChanged
AddHandler DataGridView1.CurrentCellDirtyStateChanged, AddressOf DataGridView1_OnCurrentCellDirtyStateChanged
Dim filename As String
filename = "/path/to/file"
Dim sr As New IO.StreamReader(filename)
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
cmb.Items.Add(newline(0))
'newrow.ItemArray = {newline(1)}
dt.Rows.Add(newrow)
dicItems.Add(newline(0), newline.Skip(1))
End While
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_OnCellValueChanged(ByVal s As Object, ByVal e As DataGridViewCellEventArgs)
If e.ColumnIndex = 0 Then
Dim changedCell = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
For i As Integer = 0 To dt.Columns.Count
dt.Rows(e.RowIndex).Item(i) = dicItems(changedCell.Value.ToString)(i) **error here**
Next
End If
End Sub
Private Sub DataGridView1_OnCurrentCellDirtyStateChanged(ByVal s As Object, ByVal e As EventArgs)
If DataGridView1.IsCurrentCellDirty Then
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
- 他在他的样本上使用了分号,但我坚持使用逗号。 :)
错误显示Cannot find column 2,或者当我调整某些内容时,错误在同一行变成The given key was not present in the dictionary
【问题讨论】:
标签: vb.net csv datagridview