我目前正在使用VB.NET express for desktop,2013。我很难将SQL数据绑定到带有数组的循环上的某些datagridviews。我收到一个对象null错误,因为在直接投射线上它没有拉动datagridview。我在选项卡控件工具上有多个datagridviews,每个选项卡有一个datagridview。这是我的代码:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="700"
android:fillBefore="false"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="0.0"
android:toYScale="0.0" />
</set>
错误在线
try
Dim array() As Integer = {"2", "3", "4", "7", "8", "10", "11", "12"}
For Each value As Integer In array
Dim RelativeDGV = DirectCast(Me.Controls("DataGridLine" & value), DataGridView)
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM tableA where LineNumber = @LineNumber", conn1)
comm1.Parameters.AddWithValue("@LineNumber", value)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
RelativeDGV.DataSource = dt
End Using
conn1.Close()
End Using
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
但是在
之前,空错误不会触发 Dim RelativeDGV = DirectCast(Me.Controls("DataGridLine" & value), DataGridView)
答案 0 :(得分:1)
尝试使用DataGridView
列表,如下所示:
Try
Dim array() As DataGridView = {DataGridLine2, DataGridLine3, DataGridLine4, DataGridLine7, DataGridLine8, DataGridLine10, DataGridLine11, DataGridLine12}
For Each RelativeDGV As DataGridView In array
Dim value As Integer = Regex.Replace(RelativeDGV.Name, "[^0-9]+", String.Empty)
'or like this
'Dim value As Integer = RelativeDGV.Name.Substring(12, RelativeDGV.Name.Length - 12)
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM tableA where LineNumber = @LineNumber", conn1)
comm1.Parameters.AddWithValue("@LineNumber", value)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
RelativeDGV.DataSource = dt
End Using
conn1.Close()
End Using
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
答案 1 :(得分:1)
如果各种DGV控件位于其他选项卡上,则它们不在Me.Controls
中。因为你知道这个名字,所以你可以迭代它们的数组,而不是将它们捕获并抛出它们。您也不需要为每个都创建新连接,也不需要为每个数据表创建重复的数据表:
Dim dgvCtrls As DataGridView() = {DataGridLine2, DataGridLine3, DataGridLine4}
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM...", conn1)
' ...
dt.Load(comm1.ExecuteReader())
End Using
conn1.Close()
End Using
For Each dgv In dgvCtrls
dgv.DataSource = dt
Next
如果您不希望每个网格自动反映其他网格中所做的更改,则您只需要8个相同的DataTable。为此,请在同一连接上使用数据集来创建表:
Dim SQL = "..."
Dim dgvCtrls As DataGridView() = {dgv5, dgv2, dgv3,...}
Dim ds = New DataSet
Using dbcon As New SqlConnection(SQLConnStr)
Using cmd As New SqlCommand(SQL, dbcon)
dbcon.Open()
For n As Int32 = 0 To dgvCtrls.Count - 1
ds.Load(cmd.ExecuteReader, LoadOption.OverwriteChanges, dgvCtrls(n).Name)
Next
End Using
End Using
For Each dgv In dgvCtrls
dgv.DataSource = ds.Tables(dgv.Name)
Next