Load data from sql to a list view VB

0

Good, I would like the data in my Rubro table to be loaded as columns. But so far I can not visualize in my list view.

This is the current code:

   Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ListView1.Columns.Add("Ultima Cuota", 100, HorizontalAlignment.Center)
        ListView1.Columns.Add("Numero de Credito", 100, HorizontalAlignment.Center)
        ListView1.Columns.Add("Numero de Cuota", 100, HorizontalAlignment.Center)

        conn = New SqlConnection("Data Source=conexion;Initial Catalog=BD;User ID=usuario;Password=contrasena")
        Dim strQ As String = String.Empty
        strQ = "select top 2 Descripcion from credito..Rubro WHERE IdRubro NOT IN (41,42,44,45,1056,1057,1058,48,43) "
        cmd = New SqlCommand(strQ, conn)
        da = New SqlDataAdapter(cmd)
        ds = New DataSet
        da.Fill(ds, "Rubros")
        Dim i As Integer = 0
        Dim j As Integer = 0
        'Dim mycb As New CheckBox
        ListView1.View = View.Details
        ListView1.CheckBoxes = True
        ListView1.Columns(0).DisplayIndex = ListView1.Columns.Count - 1


        'ListView1.Controls.Add(mycb)
        ' adding the columns in ListView
        For i = 0 To ds.Tables(0).Rows.Count - 1
            For j = 0 To ds.Tables(0).Columns.Count - 1
                Dim LSet = Me.ListView1.Columns.Add(ds.Tables(0).Rows(i)(j).ToString())
                ListView1.Columns.Add("Check", 60, HorizontalAlignment.Center)

                LSet.Width = 208

            Next


                'Now adding the Items in Listview
                'For i = 0 To ds.Tables(0).Rows.Count - 1
                'For j = 0 To ds.Tables(0).Columns.Count - 1
                'itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
            Next
            'ListView1.Controls.Add(mycb)
            'Dim lvi As New ListViewItem(itemcoll)
            'Me.ListView1.Items.Add(lvi)
            'Next
    End Sub

    
asked by PieroDev 20.02.2017 в 17:26
source

1 answer

2

To load your ListView using your SQL database , you will first need to make a query ... and that same query, store it inside a DataTable object, so finally you only have to travel with a For Each (or any repetitive cycle that is more comfortable). Personally I prefer this to travel DataTables.

I'm going to use Microsoft Access as a database ... just do not worry about this, because the procedure to extract data is exactly the same.

  • First of all ... Define a base class with which you are going to make your queries ... I have already defined mine called Access , with its respective connection . I'm just going to need to use the following function:

    Protected Friend Function SelectQuery(ByVal query As String) As DataTable
        Dim tabla As New DataTable
        con.Open()
    Try
        comando = New OleDbCommand(query, con)
        adapter = New OleDbDataAdapter(comando)
        adapter.Fill(tabla)
        comando.Dispose()
        adapter.Dispose()
    Catch ex As Exception
        MsgBox("Error en la consulta: " + ex.Message, MsgBoxStyle.Critical)
    End Try
        con.Close()
        Return tabla
    End Function
    
  • What this function consists of ... well, as you can see, this function is of type DataTable and will need a parameter that will be the query (String) to your database. data.

    • First, the function declares an object of the DataTable class and opens the connection to the database.
    • We then go inside a Try Catch . Initializing a class attribute called command, instance of the OleDbCommand class (which in your case, when using SQL, must be SqlCommand ), passing it as parameter our query and our connection.
    • After that, we initialize another class attribute named adapter, instance of the OleDbDataAdapter class (which in your case, must be SqlDataAdapter ), passing it as parameter our OleDbCommand object.
    • We use the Fill method, passing it our DataTable object as a parameter. Here our data filling adapter using the received query and will connect to your database thanks to the last connection.
    • We remove objects (command / adapter) and free up memory with Dispose , since everyone's duty has ended.

    Now we move on to the next step, which is very simple, when we go to request data for our ListView. As an example, I'm going to capture all this data from this table.

    Public Class DemoClassListView
    Dim admin As New Acceso
    Private Sub DemoClassListView_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListView1.View = View.Details
    
        ListView1.Columns.Add("Id_Cliente", 75, HorizontalAlignment.Center)
        ListView1.Columns.Add("Empresa", 150, HorizontalAlignment.Center)
        ListView1.Columns.Add("Direccion", 150, HorizontalAlignment.Center)
        ListView1.Columns.Add("Correo", 150, HorizontalAlignment.Center)
    
        For Each itm In admin.SelectQuery("SELECT Id_Cliente, Empresa, Direccion, Correo FROM Cliente").Rows
            Dim obj As New ListViewItem(itm(0).ToString)
            obj.SubItems.Add(itm(1).ToString)
            obj.SubItems.Add(itm(2).ToString)
            obj.SubItems.Add(itm(3).ToString)
            ListView1.Items.Add(obj)
        Next
    End Sub
    End Class
    

    Note that we first had to build our ListView without data. And then proceed to tour our DataTable, I want you to pay close attention to this line here because it is key:

    For Each itm In admin.SelectQuery("SELECT Id_Cliente, Empresa, Direccion, Correo FROM Cliente").Rows
    

    This is the declaration of our cycle for each. Where we create a temporary object that will capture the data contained in the rows of our DataTable.

    Within the cycle:

    Dim obj As New ListViewItem(itm(0).ToString)
        obj.SubItems.Add(itm(1).ToString)
        obj.SubItems.Add(itm(2).ToString)
        obj.SubItems.Add(itm(3).ToString)
        ListView1.Items.Add(obj)
    

    Since we have captured the row in our "temporary variable" itm , we will show you the column according to its index ... it works exactly like the fixes. The columns that you select in your query will always start from 0.

    Customer_ID = 0, Company = 1, Address = 2, Mail = 4, ColumnQueSigue = 5 ... and so on.

    Likewise, if you are too lazy to do it this way, you can simply write the name of each column :

    Dim obj As New ListViewItem(itm("Id_Cliente").ToString)
            obj.SubItems.Add(itm("Empresa").ToString)
            obj.SubItems.Add(itm("Direccion").ToString)
            obj.SubItems.Add(itm("Correo").ToString)
            ListView1.Items.Add(obj)
    

    And our final product:

    The generally recommended, when working with this level of database, is to use DataGrids ... you would not even have the need to build the columns ... you can select the columns you want. Make a JOIN to your liking without having to add columns before ... for example ...

        
    answered by 20.02.2017 / 19:59
    source