繁体   English   中英

vb.net 如何在列表框中显示 DB 值?

[英]vb.net How do to display DB values on a listbox?

我正在尝试在列表框中显示具有两列值的多行,因此当用户选择一个选项时,他们会有一些额外的信息。

它应该是这样的:

ej. 3 BestBuy

我使用相同的方法将数据输出到我的 GridViews,但它不会在列表框中显示任何内容。 将数据从数据库输出到列表框的正确方法是什么。

SQL 控制类函数

Public Function ExecQuery(query As String) As DataTable

    Dim DBDT = New DataTable
    Using DBCon As New SqlConnection(ConStr),
            DBCmd As New SqlCommand(query, DBCon)
        Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
        Params.Clear()
        DBCon.Open()
        DBDT.Load(DBCmd.ExecuteReader)
    End Using
    Return DBDT
End Function

'Add Params
Public Sub AddParam(Name As String, Value As Object)
    Dim NewParam As New SqlParameter(Name, Value)
    Params.Add(NewParam)
End Sub

我如何尝试将数据添加到列表框

Protected Sub DivisionListBox_DataBinding(sender As Object, e As EventArgs) Handles DivisionListBox.DataBinding

    Try
        dt = SQL.ExecQuery("Select STR_GRP_ID, GROUP_DESC
                            FROM Store_Group_Desc ")

    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    End Try

    DivisionListBox.DataSource = dt
    DivisionListBox.DataBind()
End Sub

我要做的是返回STR_GRP_ID并创建一个连接STR_GRP_IDGROUP_DESC字段的STR_GRP_ID GROUP_DESC

然后,您可以像正在执行的操作一样将 DataTable 绑定到 ListBox,但指定 ListBox 的 DisplayMember 是您的别名列,而 ValueMember 是 id:

Try
    dt = SQL.ExecQuery("Select STR_GRP_ID, CONCAT_WS(' ', STR_GRP_ID, GROUP_DESC GROUP_DESC) AS DisplayText FROM Store_Group_Desc;")
Catch ex As Exception
    MessageBox.Show(ex.Message)
    Return
End Try

With DivisionListBox
    .DataSource = dt
    .DisplayMember = "DisplayText"
    .ValueMember = "STR_GRP_ID"
End With

我认为DataBinding事件永远不会在您的代码中被触发。 您可以在事件内设置一个断点,看看它是否曾经被触发。

我选择使用Page.Load事件来填充列表框。 我将实际填充列表框的用户界面代码与数据访问代码分开。

我让服务器完成构建您想要显示的字符串的工作。 我假设 id 字段是某种类型的数字字段,所以我将它转换为 varchar。 然后添加了一个空格和描述字段。 这个新的选择字段称为 IDDesc。

IDDesc 是我想在列表框中显示的字段名称。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        FillListBox()
    End If
End Sub

Private Sub FillListBox()
    Dim ListBoxData = GetListBoxData()
    ListBox1.DataTextField = "IDDesc"
    ListBox1.DataSource = ListBoxData
    ListBox1.DataBind()
End Sub

Private Function GetListBoxData() As DataTable
    Dim DBDT = New DataTable
    Dim Query = "Select Cast(STR_GRP_ID As varchar) + ' ' + GROUP_DESC As IDDesc
                        FROM Store_Group_Desc "
    Using DBCon As New SqlConnection(ConStr),
            DBCmd As New SqlCommand(Query, DBCon)
        DBCon.Open()
        DBDT.Load(DBCmd.ExecuteReader)
    End Using
    Return DBDT
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM