迭代通过字符串的通用列表的问题
问题描述:
我在我的程序中有以下代码,我点击一个SQLCe数据库将结果追加到列表中。该部分起作用,但不是退出函数'QueryDB',而是转到else语句并再次运行该函数,该函数将返回空值。我之所以这样设计,是因为我想检查数据库是否在我尝试执行SQL语句之前打开数据库,如果它未打开,请调用该方法打开它并再次运行该函数。迭代通过字符串的通用列表的问题
Public Function QueryDB(ByVal strSQL As String) As List(Of String)
Dim reader As SqlCeDataReader
Dim results As New List(Of String)
Using cmdAdd As New SqlCeCommand(strSQL, conn)
If Me.checkConnection Then
reader = cmdAdd.ExecuteReader()
Do While reader.Read
results.Add(reader.GetString(0))
Loop
Return results
Exit Function
Else
connectPlansdb()
QueryDB(strSQL) 'does not exit function when done and goes through the function again
End If
End Using
End Function
第二个问题我已经是当我尝试填充列表进入我的表格类的组合框,我调出该数据库,并使用返回列表来填充我的组合框。我似乎无法弄清楚如何让代码处理清单。
Private Sub cmbInvestmentStrategy_DropDown(sender As System.Object, e As System.EventArgs) Handles cmbInvestmentStrategy.DropDown
Dim strat As New clsInvestmentStrategies()
Dim invStrat As New List(Of String)
invStrat = strat.getInvestmentStrategies() 'String cannot be converted to List(pf String)
cmbInvestmentStrategy.Items.Add(invStrat) 'Error 3 Value of type 'System.Collections.Generic.List(Of String)' _
'cannot be converted to '1-dimensional array of Object'.
End Sub
任何帮助将不胜感激。
谢谢!
答
你的QueryDB方法有一个很大的缺陷。如果数据库不可用(连接问题,数据库脱机或连接字符串错误),则会出现无限循环。你的查询DB方法应该只是查询数据库。您可以将其包装在另一个负责连接到数据库的方法中,但不希望无限重试数据库连接。
至于你的第二个方法:
invStrat = strat.getInvestmentStrategies() 'String cannot be converted to List(Of String)
错误是很清楚这里。 getInvestementStrategies返回单个字符串,不能转换为列表。它应该返回一个List(Of String),或者至少是一些字符串集合,我想呢?
cmbInvestmentStrategy.Items.Add(invStrat) 'Error 3 Value of type 'System.Collections.Generic.List(Of String)' _
'cannot be converted to '1-dimensional array of Object'.
Items.Add
会将单个元素添加到组合框中。您应该遍历invStrat值,并为每个项目调用Add。或者,您可以使用AddRange方法,但此方法需要一个数组,而不是一个列表。
非常感谢您的帮助! – 2012-01-28 17:19:52