我有一个DataGridView
,有2列。第一列填充了文件夹路径,第二列为空。每个文件夹路径中都有一个名为DB1的数据库。我想从每个数据库中提取1个值(VALUE),然后将该值放在第二列的相应数据库路径旁边。这是我正在使用的查询
Select CODE, VALUE from DB1 where CODE = 2419
我知道如何填充DataGridView
以及如何从数据库中提取1个值,但是我不知道从哪里开始。
修改
我设法创建了工作循环,但不知道如何将这些值添加到datagridview中的相应位置。
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = @CODE", con)
cmd.Parameters.AddWithValue("@CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
MsgBox(reader("VALUE"))
End While
End Using
End Using
End Using
Next
编辑2
使用上面的代码,我获得了msgbox中的所有值。剩下的就是插入另一个循环来将所有这些值(从第0行开始)放到datagridview中。 如果我用
替换msgboxFor i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (reader("VALUE"))
Next
然后所有行都只填充最后一个值(来自最后一个数据库的值)。
编辑3 我已经改变了
value = reader.Read()
带
While (reader.Read())
value = reader("VALUE")
End While
答案 0 :(得分:2)
我仍然不确定您的查询是如何工作的,但假设确实如此,我已经更改了您的代码。
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Dim value as string = "" ' declare a string variable to hold the result
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = @CODE", con)
cmd.Parameters.AddWithValue("@CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
value = reader.Read()
End Using
End Using
End Using
row.Cells(1) = value ' put it in the datagridview cell
Next
答案 1 :(得分:0)
在行绘制时填写..
Protected Sub GridView1_RowDataBound(sender As Object, e As _
System.Web.UI.WebControls.GridViewRowEventArgs) Handles _
GridView1.RowDataBound
Dim DGRow As GridViewRow = sender
If DGRow.RowType = DataControlRowType.DataRow Then
Dim TestPath As String = DGRow.Cells(0).Text
Dim FoundKey As String = GetKeyFromOtherDatabase(TestPath)
DGRow.Cells(1).Text = FoundKey
End If
End Sub
Private Function GetKeyFromOtherDatabase(testpath) As String
Dim FoundKey As String = ""
' FoundKey = Double something magical...
Return FoundKey
End Function