[英]DataTable: How to get item value with row name and column name? (VB)
[英]Am I loading datatable twice & update row item with boolean value
我在模塊中調用以下函數
公共函數GetExcelData(ByVal ExcelFile As String)As System.Data.DataTable
然后我有以下代碼
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
gblCompName = openFileDialog1.FileName
End If
Dim reader As New DataTableReader(GetExcelData(gblCompName))
Dim table As New DataTable
table.Load(reader)
table.Columns.Add("Single", GetType(Boolean), False)
table.Columns.Add("CouplesInFinal", GetType(Int32))
table.Columns.Add("EvtNum", GetType(String))
table.Columns.Add("EvtStruct", GetType(Int32))
table.Columns.Add("EvtCplID", GetType(Int32))
table.Columns.Add("CouplesInClass", GetType(Int32))
table.Columns.Add("Valid", GetType(Boolean), True)
Dim result() As DataRow = table.Select("[class]" Like "Single")
For Each row In result
If row.Item("Class") Like "Single" Then
table.Rows(0)("Single") = True
End If
Next
DataGridView1.DataSource = table
我的邏輯告訴我,我要兩次加載表,並且數據行字段“ Single”是布爾值,如果字符串字段“ class”類似於“ Single”,則我嘗試將其更新為True
我意識到這是兩個問題,但是加載速度似乎很慢,而且都是一種形式的程序。 任何對此的建議將非常受歡迎,謝謝
Dim reader As New DataTableReader(GetExcelData(gblCompName))
Dim table As New DataTable
如果沒有看到GetExcelData,很難說您是否填寫兩次。 如果此函數返回填充的DataTable,則
Dim table as DataTable = GetExcelData(gblCompName)
並刪除table.Load和DataReader。 這是我針對示例數據庫更新DataTable的版本。
Private Sub TestDataTableUpdate()
Try
Using cmd As New SqlCommand("Select * From Coffees", CoffeeCn)
Dim dt As New DataTable
CoffeeCn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader
dt.Load(dr)
End Using
CoffeeCn.Close()
For index As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(index)("Name").ToString = "Cinnamon Stick" Then
dt.Rows(index)("Roast") = "N/A"
End If
Next
'The above does not update the database
Dim da As New SqlDataAdapter(cmd) 'provides the connection and Select command
Dim sqlCB As New SqlCommandBuilder(da) 'Associates the DataAdapter to the command builder
sqlCB.GetUpdateCommand() 'Retrieve the update command for the DataAdapter
'Note: the DataAdapter opens and closes the connection for you
da.Update(dt) 'This updates the database by finding the changed rows in the datatable
'and running the Update command
dt.AcceptChanges() 'Reset the row status to unchanged
DataGridView1.DataSource = dt
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
CoffeeCn.Close()
End Try
End Sub
PS。 我也是自學成才的。
我要工作的表更新方法是
Dim i As Integer = 0
For i = 0 To table.Rows.Count - 1
If table.Rows(i)("Class") Like "*Single*" Then
table.Rows(i)("Single") = True
End If
Next
我在此線表上刪除了“,False”。Columns.Add(“ Single”,GetType(Boolean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.