User2341
User2341

Reputation: 45

show data in listview from database on form load

Im new in using listview on vb.net, but i managed to show the data from mysql database, but somehow i got not an error but somethings strange happening on my list view.

this is the 1st image of the listview, enter image description here

but after i click the exit button and open it again. this happens enter image description here

the columns in listview doubles, every time i exit and re-open it again, but if i close the whole application and re-run it again, it back to normal and double again every time I click the exit and open the inventory again.

this is the code on form load.

Private Sub main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Timer1.Enabled = True
    Call LVWloader()
    Call Locker(True)
    Call objLocker(False)


    With ListView1.Columns
        .Add("Semen ID", 50, HorizontalAlignment.Center)
        .Add("Bullname", 150, HorizontalAlignment.Center)
        .Add("Breed", 150, HorizontalAlignment.Center)
        .Add("Quantity", 50, HorizontalAlignment.Center)
        .Add("Location", 50, HorizontalAlignment.Center)
        .Add("Date Purchased", 50, HorizontalAlignment.Center)

    End With
    For i As Integer = 0 To ListView1.Columns.Count - 1
        ListView1.Columns(i).Width = -2
    Next i
End Sub

and this is the loader code

Public Sub LVWloader()
    Dim myCommand As New MySqlCommand
    Dim myReader As MySqlDataReader
    Dim conn As MySqlConnection
    conn = New MySqlConnection
    conn.ConnectionString = "server = localhost;username= root;password= a;database= semenis"
    Try
        conn.Open()
    Catch mali As MySqlException
        MsgBox("connot establish connection")
    End Try

    ListView1.Items.Clear()
    With myCommand
        .Connection = conn
        .CommandText = "Select * from inventory"
    End With
    myReader = myCommand.ExecuteReader
    While myReader.Read()
        With ListView1
            .Items.Add(myReader(0))
            With .Items(.Items.Count - 1).SubItems
                .Add(myReader.Item(1))
                .Add(myReader.Item(2))
                .Add(myReader.Item(3))
                .Add(myReader.Item(4))
                .Add(myReader.Item(5))

            End With
        End With
    End While
End Sub

i think the code error comes from .Add for listview, maybe theres an alternative way in doing this?

im using vb.net and mysql as database

thanks,

Upvotes: 0

Views: 3275

Answers (1)

Whitey
Whitey

Reputation: 431

The reason why it's duplicating is because you are using the form's Load event to add the columns, which is called each time the form is loaded. You need to either add the columns in the form designer or in the form's constructor.

Upvotes: 2

Related Questions