[英]Direct Cast giving null error for datagridview
我目前正在2013年面向台式機的VB.NET Express中工作。我很難將SQL數據綁定到具有數組的循環上的某些datagridviews。 我收到一個對象為null的錯誤,這是因為在直接投射線上沒有拉出datagridview。 我在一個標簽頁控制工具上有多個datagridviews,每個標簽頁一個datagridview。 這是我的代碼:
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)
但是直到出現空錯誤才觸發
RelativeDGV.DataSource = dt
嘗試像這樣使用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
如果各種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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.