如何在VB中的数据表中添加基于现有列的新列?
问题描述:
我试图建立一个代码来处理从指纹机到报告文本文件。如何在VB中的数据表中添加基于现有列的新列?
文本文件输入例如,
001;0000000000200004;01-07-2016;15:31;01;01
用分号分隔符,
machinecode;personid;dateDD-MM-YYYY;timeHH:MM;jobid;unused
这是我最后一次成功的代码
Imports System.IO
Imports System.Windows.Forms
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lines = IO.File.ReadAllLines("C:\Users\Adventa\Documents\Visual Studio 2010\Projects\AbsensiALU\AbsensiALU\Absen.txt")
Dim tblabsen = New DataTable
Dim colCount = lines.First.Split(";"c).Length
For i As Int32 = 1 To colCount
'Dim header As String
tblabsen.Columns.Add(New DataColumn("Column_" & i, GetType(String)))
Next
For Each line In lines
Dim objFields = From field In line.Split(";"c)
Dim newRow = tblabsen.Rows.Add()
newRow.ItemArray = objFields.ToArray()
Next
Dim table1 As New DataTable
table1 = tblabsen.Copy()
table1.Columns(0).ColumnName = "No. Mesin"
table1.Columns(1).ColumnName = "NIK"
table1.Columns(2).ColumnName = "Tanggal"
table1.Columns(3).ColumnName = "Jam"
table1.Columns(4).ColumnName = "Keterangan"
DataGridView1.DataSource = table1
DataGridView1.AutoResizeColumn(0)
DataGridView1.AutoResizeColumn(1)
DataGridView1.AutoResizeColumn(2)
DataGridView1.AutoResizeColumn(3)
DataGridView1.AutoResizeColumn(4)
DataGridView1.Columns(5).Visible = False
Dim rowData As String = ""
'dt is the name of the data table
For Each row As DataRow In table1.Rows
For Each column As DataColumn In table1.Columns
rowData = rowData & column.ColumnName & "=" & row(column) & " "
Next
rowData = rowData & vbNewLine & vbNewLine
Next
End Sub
Private Sub DataGridView1_CellContentClick_1(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
现在我想添加一个柱成它,基于table1.columns(4)配有可能是一个IF/CASE操作者,因此,例如在新的列将是这样
Dim kete As String
Select Case tblabsen.Columns(4).GetType.ToString()
Case "00"
kete = "Masuk"
Case "01"
kete = "Pergi"
Case "02"
kete = "Kembali"
Case "03"
kete = "Pulang"
Case Else
kete = "Error"
End Select
假定“凯泰”可被写入到新列。
在此先感谢。
答
你必须创建自己的DataTable
,所以你需要额外添加一列第一
For i As Int32 = 1 To colCount + 1
'Dim header As String
tblabsen.Columns.Add(New DataColumn("Column_" & i, GetType(String)))
Next
之后,你需要在ForEach
For Each line In lines
Dim objFields = line.Split(";"c).ToList()
Dim newRow = tblabsen.Rows.Add()
Dim kete As String
Select Case objField(4).GetType.ToString()
Case "00"
kete = "Masuk"
Case "01"
kete = "Pergi"
Case "02"
kete = "Kembali"
Case "03"
kete = "Pulang"
Case Else
kete = "Error"
End Select
objFields.Add(kete)
newRow.ItemArray = objFields.ToArray()
Next
分配你的价值,你也需要处理这个额外的列在你的代码的其余部分(即调整大小,列名称)
感谢您的答复亚历克斯,它确实解决了我添加新列的问题,但吨他新列或'kete'值总是“错误”,或者我们可以说SELECT操作符不工作,我不知道它。也许我还必须弄清楚如何提取单个单元格或列以供将来参考。 –
@JoeAdventa你有没有试过在调试模式下看看你有什么?我相信我们可以省略'.GetType.ToString()' – *er
我只是删除'.GetType.ToString()',它的工作。现在,我必须在添加新列变量之前了解计算值。非常感谢Alex。 –