简体   繁体   中英

All Listview data show in textbox using loop

    Dim Mysqlconn = New SqlConnection
    Mysqlconn.ConnectionString = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"

    Dim dt As DataTable = New DataTable("studentdata")

    Mysqlconn.Open()

    Dim query As String
    query = "select ID from studentdata where Class='" & ComboBox1.Text & "'"

    Dim Command = New SqlCommand(query, Mysqlconn)
    Dim dr = Command.ExecuteReader(CommandBehavior.CloseConnection)

    ListView1.Items.Clear()
    Dim x As ListViewItem

    Do While dr.Read = True
        x = New ListViewItem(dr("ID").ToString)
        ListView1.Items.Add(x)
    Loop

    For i = 0 To ListView1.Items.Count - 1
        TextBox1.Text = ListView1.Items(i).SubItems(0).Text
    Next

In this code, Textbox1 is showing the last row from Listview1 . My requirement is all the Listview1 data show in textbox1 one after one from Listview1. Is this possible to show in textbox1 read all data from Listview1 using loop. Thank you...

A textbox only holds one string at a time. If it's set to allow multiline strings (not clear in the question) you can separate each item with a linebreak. Otherwise you can separate the strings using a delimiter like a comma.

Dim query As String = "select ID from studentdata where Class= @class"
Using conn As New SqlConnection("Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"), _
      cmd  As New SqlCommand(query, conn)

    cmd.Parameters.Add("@class", SqlDbType.NVarChar, 20).Value =  ComboBox1.Text
    conn.Open()
    Using dr As SqlDataReader = cmd.ExecuteReader()
        While dr.Read()
            ListView1.Items.Add(New ListViewItems(dr("ID").ToString()))
        End While
    End Using
End Using

TextBox1.Text = String.Join(",", ListView1.Items.Select(Function(i) i.SubItems(0).Text))

Also note how I used a query parameter to include the combobox value in the SQL command. That's a big deal ; anything else will give you trouble, usually sooner than later.

Using as loop, the proper way would be like so:

Dim lines As New List(Of String)

For i = 0 To ListView1.Items.Count - 1
    lines.Add(ListView1.Items(i).Text)
Next

TextBox1.Lines = lines.ToArray()

You can't keep setting the Text property to a new value and expect the old value to hang around for no reason. You could append to the Text each time, but that is inefficient. The proper way is to create a list of the values, convert that to a String array and then assign that to the Lines property.

Note that there is no point getting the Text of the first subitem because that is the same as the Text of the item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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