2012-05-22 118 views
0

嗨,我有字符串和整數,一些值分配給。現在我需要閱讀的字符串和整數值,並將它們分配給我所使用VB.Net創建的數據表..VB.Net爲數據表賦值

If dt.Rows.Count > 0 Then 
For n As Integer = 0 To dt.Rows.Count - 1 
EmployeeNo = (dt.Rows(n)(0)) 
EmpName = (dt.Rows(n)(1)).ToString 
Commission = CDbl(dt.Rows(n)(2)) 
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission] 
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns.. 
Next 
End If 

請幫我在這..

+0

我佈置了一些值從excel中讀取一些變量。現在我需要將這些值逐個分配給數據表。所以在這種情況下,我需要幫助通過讀取值在表上逐行填充。那麼完整的表格應該保存到數據庫 – Bramenath

+0

把你的代碼有問題保存到DataTable的數據.. –

回答

1

試試這個傾倒整個表到數據表:

var connectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";" 
     var sheetName = "Sheet1"; 

     using (var con = new OleDbConnection(connectionString)) 
     { 
      con.Open(); 

      var table = new DataTable(sheetName); 
      var query = "SELECT * FROM [" + sheetName + "]"; 
      OleDbDataAdapter adapter = new OleDbDataAdapter(query, con); 
      adapter.Fill(table); 
      return table; 
     } 

編輯:根據更新的問題

If dt.Rows.Count > 0 Then 
For n As Integer = 0 To dt.Rows.Count - 1 
EmployeeNo = (dt.Rows(n)(0)) 
EmpName = (dt.Rows(n)(1)).ToString 
Commission = CDbl(dt.Rows(n)(2)) 
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission] 
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns.. 

Dim dataRow As DataRow = DtEmployee.Tables("Employee").AsEnumerable().Where(Function(row) row.Field(Of String)("EmpNo") = EmployeeNo).SingleOrDefault() 
If dataRow IsNot Nothing Then 

//Set your DataRow 
dataRow("EmpName") = EmpName 
dataRow("Commission ") = Commission 
DtEmployee.AcceptChanges(); 
End If 

Next 
End If 

查找從划船DtEmployee表和更新的一個或如果要添加新行,然後不找行,只要創建新行與設定值,並加入到DtEmployee

DataRow dataRow = DtEmployee.Tables("Employee").NewRow() 
//Set your DataRow 
dataRow("EmpName") = EmpName 
dataRow("Commission ") = Commission 
DtEmployee.Tables("Employee").Rows.Add(dataRow) 

希望這有助於..

+0

如果dt.Rows.Count> 0 Then For n As Integer = 0 To dt.Rows.Count - 1 爲employeeno =(dt.Rows(n)的(0)) EmpName =(dt.Rows(N)(1))。的ToString 委員會= CDbl(dt.Rows(n)的(2)) \t \t \t \\我需要逐一閱讀並將[EmployeeNo,EmpName,Commission]分配給數據集DtEmployee,其中員工是表格,EmpNo,EmpName,Commission是coloumns .. \t \t下一頁 結束如果 – Bramenath

+0

檢查更新的答案 –

+0

雅感謝..它的工作完美... – Bramenath