将两列值添加到 vb.net 中的列表框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15446674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:45:11  来源:igfitidea点击:

Adding two column values to listbox in vb.net

vb.net

提问by user2176431

I have a table named users which has the following columns in it

我有一个名为 users 的表,其中包含以下列

User_id,user_name,user_pwd,First_Name,Middle_Name,Last_Name and user_type.

I have dataset named dst and created a table called user in the dataset. Now I want to populate listbox with user_Name, First_Name, Last_nameof each and every row in the table user.

我有一个名为 dst 的数据集,并在数据集中创建了一个名为 user 的表。现在我想填充列表框user_NameFirst_NameLast_name每表中的用户每一行的。

I am able to add one column value at a time but not getting how to add multiple column values of each row to listbox

我可以一次添加一个列值,但不知道如何将每行的多个列值添加到列表框

Dim dt As DataTable = Dst.Tables("user")

For Each row As DataRow In dt.Rows
    lstUsers.Items.Add(row("User_Name"))
Next

Above code works perfectly but I also want to add First_name as well as last_name to the list box at the same time.

上面的代码工作得很好,但我也想同时将 First_name 和 last_name 添加到列表框中。

回答by Fabio

Use same approach as you have, but put all values you want in one string.

使用与您相同的方法,但将您想要的所有值放在一个字符串中。

Dim dt As DataTable = Dst.Tables("user")

For Each row As DataRow In dt.Rows
    Dim sItemTemp as String
    sItemTemp = String.Format("{0},{1},{2}", row("User_Name"), row("First_Name"), row("Last_Name"))
    lstUsers.Items.Add(sItemTemp)
Next

String.Format()function will call .ToString()on all parameters.

String.Format()函数将调用.ToString()所有参数。

In this case if row(ColumnName)is NULL valuethen .ToString()return just empty string

在这种情况下,如果row(ColumnName)NULL value.ToString()仅返回空字符串

回答by Don

You have 2 choices:

您有 2 个选择:

  1. Using the ListBox:
  1. 使用列表框:

To use the ListBox, set the font to one that is fixed width like courier new (so that the columns line up), and add the items like this:

要使用 ListBox,请将字体设置为固定宽度的字体,例如 courier new(以便各列对齐),然后添加如下项目:

For Each row As DataRow In dt.Rows
    lstUsers.Items.Add(RPAD(row("User_Name"),16) & RPAD(row("First_Name"),16) & RPAD(row("Last_Name"),16))
Next

The RPAD function is defined like this:

RPAD 函数定义如下:

Function RPAD(a As Object, LENGTH As Object) As String
    Dim X As Object
    X = Len(a)
    If (X >= LENGTH) Then
        RPAD = a : Exit Function
    End If
    RPAD = a & Space(LENGTH - X)
End Function

Adjust the LENGTH argument as desired in your case. Add one more for at least one space. This solution is less than ideal because you have to hard-code the column widths.

根据您的情况调整 LENGTH 参数。为至少一个空间再添加一个。此解决方案不太理想,因为您必须对列宽进行硬编码。

  1. Use a DataGridView control instead of a ListBox. This is really the best option, and if you need, you can even have it behave like a ListBox by setting the option to select the full row and setting CellBorderStyle to SingleHorizontal. Define the columns in the designer, but no need to set the widths - the columns can auto-size, and I set that option in the code below. if you still prefer to set the widths, comment out the AutoSizeColumnsMode line.
  1. 使用 DataGridView 控件而不是 ListBox。这确实是最好的选择,如果需要,您甚至可以通过设置选择整行的选项并将 CellBorderStyle 设置为 SingleHorizo​​ntal 来使其表现得像 ListBox。在设计器中定义列,但不需要设置宽度 - 列可以自动调整大小,我在下面的代码中设置了该选项。如果您仍然喜欢设置宽度,请注释掉 AutoSizeColumnsMode 行。

The code to set up the grid and add the rows goes like this:

设置网格和添加行的代码如下:

    g.Rows.Clear() ' some of the below options are also cleared, so we set them again
    g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells
    g.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal
    g.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    g.AllowUserToAddRows = False
    g.AllowUserToDeleteRows = False
    g.AllowUserToOrderColumns = True
    For Each row As DataRow In dt.Rows
        g.Rows.Add(row("User_Name"), row("First_Name"), row("Last_Name"))
    Next

回答by bonny

You might solved your problem by now but other users like me might have issue with it.
Above answers given worked for me even but I found a same answer in a simple way according to what I want..

您现在可能已经解决了您的问题,但像我这样的其他用户可能会遇到问题。
以上给出的答案甚至对我有用,但我根据我想要的方式以简单的方式找到了相同的答案。

cmd = New SqlCommand("select User_Name, First_Name, Last_Name from User")
  Dim dr As SqlDataReader = cmd.ExecuteReader(YourConnectionString)

  If dr.HasRows Then
        Do While dr.Read
                        lst.Items.Add(dr.Item(0).ToString & " " & dr.Item(1).ToString & " " & dr.Item(2).ToString)
        Loop
  End If

This worked for me, maybe wrong way but I found it simple :)

这对我有用,也许是错误的方式,但我发现它很简单:)

回答by ShieldOfSalvation

May I suggest you use a ListView control instead of Listbox?

我可以建议您使用 ListView 控件而不是 Listbox 吗?

If you make the switch, here's a sample subroutine you could use to fill it up with the data you said you want. Adapt it the way you like; there's much room for improvement but you get the general idea:

如果您进行切换,这里有一个示例子程序,您可以使用它来填充您所说的所需数据。以您喜欢的方式进行调整;有很大的改进空间,但你得到了一般的想法:

Public Sub FillUserListView(lstUsers As ListView, Dst As DataSet)

    Dim columnsWanted As List(Of String) = New List(Of String)({"User_Name", "First_Name", "Last_Name"})
    Dim dt As DataTable = Dst.Tables("user")
    Dim columns As Integer = 0
    Dim totalColumns = 0
    Dim rows As Integer = dt.Rows.Count

    'Set the column titles
    For Each column As DataColumn In dt.Columns
        If columnsWanted.Contains(column.ColumnName) Then
            lstUsers.Columns.Add(column.ColumnName)
            columns = columns + 1
        End If
        totalColumns = totalColumns + 1
    Next

    Dim rowObjects(columns - 1) As ListViewItem
    Dim actualColumn As Integer = 0

    'Load up the rows of actual data into the ListView
    For row = 0 To rows - 1
        For column = 0 To totalColumns - 1
            If columnsWanted.Contains(dt.Columns(column).ColumnName) Then

                If actualColumn = 0 Then
                    rowObjects(row) = New ListViewItem()
                    rowObjects(row).SubItems(actualColumn).Text = dt.Rows(row).Item(actualColumn)

                Else
                    rowObjects(row).SubItems.Add(dt.Rows(row).Item(actualColumn))
                End If

                lstUsers.Columns.Item(actualColumn).Width = -2  'Set auto-width

                actualColumn = actualColumn + 1
            End If
        Next

        lstUsers.Items.Add(rowObjects(row))
    Next

    lstUsers.View = View.Details 'Causes each item to appear on a separate line arranged in columns
End Sub