【问题标题】:How to enable multiple column for a listbox on VB.NET web application?如何在 VB.NET Web 应用程序上为列表框启用多列?
【发布时间】:2020-09-09 14:50:24
【问题描述】:

我想要做的是在列表框中显示两列,以便用户获得更多信息。 我填充列表框的方式是使用带有自定义查询的 SqlDataSource,然后将该数据源附加到列表框。

我的问题是在数据源中我只能选择两个值,一个用于列表框显示,另一个值是选择列表框的数据字段值。

如何在列表框上显示来自 SqlDataSource 的多个列值?

【问题讨论】:

    标签: vb.net web-applications


    【解决方案1】:

    首先为您的数据创建一个类。我添加了一个参数化构造函数,因此无需单独设置属性即可轻松创建 Coffee。我还覆盖了 .ToString 方法,因此 ListBox 将显示我想要的内容。如果您真的想要列,则可以将其填充到设定的长度。

    Public Class Coffee
        Public Property Name As String
        Public Property Type As String
        Public Sub New(cofName As String, cofType As String)
            Name = cofName
            Type = cofType
        End Sub
        Public Overrides Function ToString() As String
            Return $"{Name}, {Type}"
        End Function
    End Class
    

    要填写列表,请创建一个新咖啡并将其添加到列表中。

    Private CoffeeList As New List(Of Coffee)
    
    Private Sub FillCoffeeList()
        Using cn As New SqlConnection(My.Settings.CoffeeConnection),
                cmd As New SqlCommand("Select Top 10 Name, Type From Coffees;", cn)
            cn.Open()
            Using reader = cmd.ExecuteReader
                While reader.Read
                    Dim c As New Coffee(reader.GetString(0), reader.GetString(1))
                    CoffeeList.Add(c)
                End While
            End Using
        End Using
    End Sub
    

    然后在Page.Load中

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            FillCoffeeList()
            ListBox1.DataSource = CoffeeList
            ListBox1.DataBind()
        End If
    End Sub
    

    ListBox 对 CoffeeList 中的每个 Coffee 对象调用 .ToString 并显示我们在 Class 中确定的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多