数据访问层使用参数填充组合框

时间:2014-06-08 10:05:58

标签: vb.net combobox parameter-passing data-access-layer

我使用VB.Net(Visual Studio 2013)和N层架构来填充组合框列表。我的课程代码如下

    Public Shared Function List() As List(Of AppName.BusinessLogic.BLL_RMCodeComboClass)
    Dim dbo_RMCodeList As New List(Of AppName.BusinessLogic.BLL_RMCodeComboClass)
    Dim connTemp As SqlConnection = AppClass.GetConnection
    Dim strSelectSQL As String = "SELECT [RMCode] FROM [dbo].[RMMaster] WHERE [dbo].[RMMaster].[Category] = '" & strRMType & "'"
    Dim strCommandSelect As New SqlCommand(strSelectSQL, connTemp)
    Try
        connTemp.Open()
        Dim rdrTemp As SqlDataReader = strCommandSelect.ExecuteReader()
        Dim clsdbo_RMCodeList As AppName.BusinessLogic.BLL_RMCodeComboClass
        Do While rdrTemp.Read
            clsdbo_RMCodeList = New BusinessLogic.BLL_RMCodeComboClass
            clsdbo_RMCodeList.RMCode = System.Convert.ToString(rdrTemp("RMCode").ToString)
            dbo_RMCodeList.Add(clsdbo_RMCodeList)
        Loop
        rdrTemp.Close()
    Catch ex As SqlException
        Throw ex
    Finally
        connTemp.Close()
    End Try
    Return dbo_RMCodeList
End Function

我的目标是根据类型检索或填充带有RMCodes的组合框。因此我相应地使用了strSelectSQL。请帮我把Category的值传递给这个函数,使它变得动态。从表示/ UI层上的另一个组合框中选择Type的值,因此应根据所选的类别填充Code字段。

提前致谢 CL

1 个答案:

答案 0 :(得分:0)

E.g。

Private Function List(type As String) As List(Of Thing)
    '...

    Dim command As New SqlCommand("SELECT * FROM MyTable WHERE @Type IS NULL OR Type = @Type")

    command.Parameters.Add("@Type",
                           SqlDbType.NVarChar,
                           50).Value = If(String.IsNullOrEmpty(type),
                                          CObj(DBNull.Value),
                                          type)

    '...
End Function

这使得过滤器可选。如果传入Nothing或空String,则SQL参数为NULL且每条记录都匹配,否则结果集将按您传入的值进行过滤。