向数据表添加可变行数

时间:2013-04-23 11:14:08

标签: vb.net datatable

我有一个包含360行数据的表单。我需要将这些数据添加到数据表中。但是如果有重复,它应该只更新包含该数据的行。并且重复的数量可以在0到180之间。是否可以在vb.net 3.5中执行此操作?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:0)

您可以使用DataTable.LoadDataRow方法 这要求您定义表的主键 该方法使用主键来标识重复行

Dim dt = new DataTable("test")
Dim col = dt.Columns.Add("ID", Type.GetType("System.Int32"))
col.AllowDbNull = false
col.Unique = true
dt.Columns.Add("Name", Type.GetType("System.String"))
..... ' and so on '

' now the primary key
Dim columns(1) As DataColumn
columns(0) = dt.Columns("ID")
dt.PrimaryKey = columns

' And then the LoadDataRow
Dim newRow As Object() = New Object(1) {}
newRow(0) = Convert.ToInt32(TextBox1.Text)
newRow(1) = TextBox2.Text
dt.LoadDataRow(newRow, True)
....

如果您的一个或多个textbox1.Text包含相同的ID,则前一行将使用新值更新,否则新行将添加到数据表中

修改
在“数量”列上查看有关总和操作的注释,您应该更改方法 (当然,添加第三列,希望使用数字类型)

' Search if the ID is already present '
Dim rows = dt.Select("ID=" & TextBox1.Text)
if rows.Length == 0 Then
   ' No ID found, add a newrow to the datatable'
   Dim newRow = dt.NewRow()
   newRow(0) = Convert.ToInt32(TextBox1.Text)
   newRow(1) = TextBox2.Text
   newRow(2) = Convert.ToInt32(TextBox3.Text)
   dt.Rows.Add(newRow)
Else
   ' ID found, the Rows array should be of just one row and the second column incremented of the quantity '
   rows(0)(2) +=  Convert.ToInt32(TextBox3.Text)
End If

修改

Dim dt As New DataTable 
'adding columns to the datatble'
dt.Columns.Add("Operation") 
dt.Columns.Add("folder") 
' This is a numeric column, so tell it to the framework
dt.Columns.Add("quantity", Type.GetType("System.Int32"))

'adding datarows 
' The search is on a string column, so enclose in single quotes 
' I assume that a 'folder' names doesn't contains a single quote
Dim rows = dt.Select("folder='" & L1F1.Text + "'") 
If rows.Length = 0 Then 
   Dim newRow = dt.NewRow() 
   newRow(0) = L1Ob1.Text 
   newRow(1) = L1F1.Text 
   newRow(2) = Convert.ToInt32(L1Qty1.Text) 
   dt.Rows.Add(newRow) 
Else 
   rows(0)(2) += Convert.ToInt32(L1Qty1.Text) 
End If