迭代通用字符串列表的问题

时间:2012-01-28 15:38:47

标签: vb.net list generics combobox sql-server-ce

我的程序中有以下代码,我在SQLCe数据库中将结果附加到列表中。该部分有效,但不是退出函数' QueryDB'它转到else语句并再次运行该函数,它将返回一个空值。我设计它是这样的,因为我想检查以确保数据库在我尝试执行SQL语句之前是打开的,如果它没有打开,请调用方法打开它并再次运行该函数。 / p>

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

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的QueryDB方法有一个很大的缺陷。如果数据库不可用(连接问题,数据库脱机或连接字符串错误),则会出现无限循环。您的查询DB方法应该只查询数据库。您可以将其包装在负责连接到数据库的另一个方法中,但您不希望无限地重试数据库连接。

至于你的第二种方法:

invStrat = strat.getInvestmentStrategies() 'String cannot be converted to List(Of String)

这里的错误很明显。 getInvestementStrategies返回单个String,无法转换为列表。它应该返回一个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方法,但此方法需要一个数组,而不是List。

相关问题