2013-04-23 28 views
0

我有一個包含360行數據的表單。我需要將這些數據添加到數據表中。但是,如果有重複,它應該只更新包含該數據的行。重複次數的範圍可以從0到180.在vb.net 3.5中可以這樣做嗎?如果是這樣,怎麼樣?將可變數量的行添加到數據表中

+0

什麼是 「數據線」,你嘗試過什麼嗎? – 2013-04-23 11:16:18

+0

@Tim Schmelter:一行數據是3列數據,其中一列對我來說是最重要的,因爲我不需要它的重複。 – SaurabhSuman 2013-04-23 12:23:02

回答

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,以前的行會與否則新值的新行被更新將被添加到DataTable

編輯
看到你關於在數量列求和運算評論,那麼你應該改變方法

(當然與desidered數字類型添加第三列)
' 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 
+0

和我應該怎麼做,如果我想總結的價值? – SaurabhSuman 2013-04-23 12:21:00

+0

哪些值?這只是一個基於你的問題的僞代碼。我不能更確切地知道你的數據結構 – Steve 2013-04-23 12:26:44

+0

當然...我有3列... Id,Name和Quantity,這是一個整數...所以,如果名稱已被重複多次,這些數量需要總結......是否有可能這樣做? – SaurabhSuman 2013-04-23 12:28:58