none
Fill ListBox with datatable column RRS feed

  • Question

  • Hi all

    I'm Trying to fill a list box with a datatable column got from sql table

    This is the code I use

    Private Sub AddItemsToListBoxClienteNazione() UI_DS_Nazioni = New DataSet UI_DS_Nazioni = BLL.GetTableNazioni() 'fill dataset UI_DT_Nazioni = UI_DS_Nazioni.Tables("Nazioni")

    ' DataTable well loaded - checked with loop thru rows.

    ' now fill listbox ListBoxClienteNazione.DataSource = UI_DT_Nazioni ListBoxClienteNazione.DisplayMember = "NazioneDes" ListBoxClienteNazione.ValueMember = "NazioneSigla" For i = 0 To ListBoxClienteProvincia.Items.Count MessageBox.Show(ListBoxClienteProvincia.Items(i).ToString) Next End Sub

    The DataTable UI_DT_Nazioni is well read (I checked it)

    After loading the DataTable I check items in Listbox but each item is 

    System.Data.DatRowView

    What is wrong)

    Monday, June 4, 2018 7:11 PM

Answers

  • I solved the problem

    The ListBoxItem after Bound id DataRowView type

    So to get text value for a ListboxItem I have to Ctype

    Private Sub ListBoxClienteNazione_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBoxClienteNazione.SelectedIndexChanged
    
    
    		If ListBoxClienteNazione.SelectedIndex > -1 Then
    			Dim ItemSelected = CType(ListBoxClienteNAzione.SelectedItem.Item("NazioneDes"), String)
    			TxtClienteNazione.Text = ItemSelected
    End sub

    • Marked as answer by Claudio111 Tuesday, June 5, 2018 10:41 AM
    Tuesday, June 5, 2018 10:41 AM

All replies

  • If you are getting System.Data.DataRowView than 

    The field name is incorrect for DisplayMember, that is the only reason for that to show after loading the ListBox with DataTable.

    ListBoxClienteNazione.DisplayMember = "NazioneDes" 

    Example, my base SELECT statement is

    SELECT OrderID,
            CustomerIdentifier,
            EmployeeID,
            OrderDate,
            RequiredDate,
            ShippedDate,
            ShipAddress,
            ShipCity,
            ShipCountry
    FROM dbo.Orders

    I load the data vis

    ListBox1.DataSource = dt
    ListBox1.DisplayMember = "ShiCountry"

    Why? because I spelled ShipCountry as ShiCountry

    Make it right

    ListBox1.DataSource = dt
    ListBox1.DisplayMember = "ShipCountry"


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, June 4, 2018 9:34 PM
    Moderator
  • i changed the code in this way

    	Private Property UI_DS_Nazioni As DataSet = Nothing
    	Private Property UI_DT_Nazioni As DataTable = Nothing
    	Private Sub AddItemsToListBoxClienteNazioni()
    		
    
    		UI_DS_Nazioni = New DataSet
    		' Load Table 
    		UI_DS_Nazioni = BLL.GetTableNazioni()
    		
    			UI_DT_Nazioni = UI_DS_Nazioni.Tables("Nazioni")
    
    			ListBoxClienteNazioni.DataSource = UI_DT_Nazioni
    			Dim col As String = (UI_DT_Nazioni.Columns(1).ColumnName).ToString
    			ListBoxClienteNazioni.DisplayMember = col
    
    			'display Listbox
    			ListBoxClienteNazioni.Parent = TxtClienteNazioni.Parent
    			ListBoxClienteNazioni.Location = New Point(TxtClienteNazioni.Location.X + TxtClienteNazioni.Width - ListBoxClienteNazioni.Width,
    			TxtClienteNazioni.Location.Y + Offset1)
    			ListBoxClienteNazioni.Visible = True
    			ListBoxClienteNazioni.Focus()
    			ListBoxClienteProvincia.BringToFront()
    
    			' loop items 
    			Label8.Text = ""
    
    			For i = 0 To ListBoxClienteNazioni.Items.Count - 1
    				Label8.Text = Label8.Text & (ListBoxClienteNazioni.Items(i).ToString) & vbCrLf
    
    			Next
    		
    	End Sub

    Now the listbox is well display but if I loop trhu item , each of them is 

    System.Data.DataRowView

    Tuesday, June 5, 2018 9:39 AM
  • thank you
    Tuesday, June 5, 2018 9:42 AM
  • Why looping through the presentation if the data is exactly the same. 

    For each row in UI_DS_Nazioni.tables("Nazione").rows
    		MessageBox.Show(row(NazioneDes").ToString)
    Next


    Success
    Cor

    Tuesday, June 5, 2018 9:57 AM
  • I solved the problem

    The ListBoxItem after Bound id DataRowView type

    So to get text value for a ListboxItem I have to Ctype

    Private Sub ListBoxClienteNazione_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBoxClienteNazione.SelectedIndexChanged
    
    
    		If ListBoxClienteNazione.SelectedIndex > -1 Then
    			Dim ItemSelected = CType(ListBoxClienteNAzione.SelectedItem.Item("NazioneDes"), String)
    			TxtClienteNazione.Text = ItemSelected
    End sub

    • Marked as answer by Claudio111 Tuesday, June 5, 2018 10:41 AM
    Tuesday, June 5, 2018 10:41 AM
  • Why don't you use data binding?

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ops As New CustomerOperations
        Dim dt As DataTable = ops.GetCustomers()
        ListBox1.DataSource = dt
        ListBox1.DisplayMember = "CompanyName"
    
        TextBox1.DataBindings.Add("Text", dt, "ContactName")
    End Sub

    And if not you should consider strong typing as shown below

    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New CustomerOperations
    
            ListBox1.DataSource = ops.GetCustomers()
            ListBox1.DisplayMember = "CompanyName"
            AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            If ListBox1.SelectedItem IsNot Nothing Then
                TextBox1.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Field(Of String)("ContactName")
            End If
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, June 5, 2018 11:01 AM
    Moderator

  • And if not you should consider strong typing as shown below

    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New CustomerOperations
    
            ListBox1.DataSource = ops.GetCustomers()
            ListBox1.DisplayMember = "CompanyName"
            AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            If ListBox1.SelectedItem IsNot Nothing Then
                TextBox1.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Field(Of String)("ContactName")
            End If
        End Sub
    End Class


    Karen,

    Sorry, but in my eyes you are describing Strongly Typed in the popular way as done by persons who like non strongly typed languages. They think probably it has to do with using a keyboard. 

    To give you an example of an strongly typed dataset and the use of it in VB see next made from the code of Claudio. 

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim dt As New TestDataBaseDataSet.UiDtNazioniDataTable
            Dim ta As New TestDataBaseDataSetTableAdapters.UiDtNazioniTableAdapter
            ta.Fill(dt)
            ListBox1.DataSource = dt
            ListBox1.DisplayMember = dt.NazioneDesColumn.ColumnName
            ListBox1.ValueMember = dt.NazioneSiglaColumn.ColumnName
        End Sub
    End Class

    It has something to do with the keyboard typing, because as you can understand any keyboard typing mistake is recognized. But the text Strong is meant that no strings are used to identify a Class. This is something persons as Claudio are not able to understand because he has endless times made clear that I'm a fool and I get the idea he is feed by your kind of messages.


    Success
    Cor


    Tuesday, June 5, 2018 11:41 AM
  • Cor,

    This is what I mean by strong typed in a class

    Public Function GetCustomer(pCustomerIdentifier As Integer) As Customer
    
        Dim customer As new Customer With {.CustomerIdentifier = pCustomerIdentifier}
    
        mHasException = False
    
        Dim selectStatement As String = 
                <SQL>
                SELECT CompanyName
                        ,ContactName
                        ,ContactTitle
                        ,StreetAddress
                        ,City
                        ,PostalCode
                        ,Country
                        ,Phone
                        ,JoinDate
                        ,ActiveStatus
                FROM dbo.Customers
                WHERE CustomerIdentifier = @CustomerIdentifier
                </SQL>.Value
        Using cn = New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd = New SqlCommand With {.Connection = cn}
    
                cmd.CommandText = selectStatement
                cmd.Parameters.AddWithValue("@CustomerIdentifier", pCustomerIdentifier)
    
                Try
                    cn.Open()
    
                    Dim reader As SqlDataReader = cmd.ExecuteReader()
                    If reader.HasRows Then
    
                        reader.Read()
    
                        customer.CompanyName = reader.GetString(0)
                        customer.ContactName = reader.GetString(1)
                        customer.ContactTitle = reader.GetString(2)
                        customer.StreetAddress = reader.GetString(3)
                        customer.City = reader.GetString(4)
                        customer.PostalCode = reader.GetString(5)
                        customer.Country = reader.GetString(6)
                        customer.Phone = reader.GetString(7)
                        customer.JoinDate =reader.GetDateTime(8)
                        customer.ActiveStatus = reader.GetBoolean(9)
    
                    End If
                Catch ex As Exception
    
                    mHasException = True
                    mLastException = ex
    
                End Try
    
            End Using
        End Using
            
        Return customer
    
    End Function

    Public Class Customer
        Public Property CustomerIdentifier() As Integer
        Public Property CompanyName() As String
        Public Property ContactName() As String
        Public Property ContactTitle() As String
        Public Property StreetAddress() As String
        Public Property City() As String
        Public Property PostalCode() As String
        Public Property Country() As String
        Public Property Phone() As String
        Public Property JoinDate() As Date
        Public Property ActiveStatus() As Boolean
        Public Overrides Function ToString() As String
            Return $"{CustomerIdentifier} - {CompanyName}"
        End Function
    End Class

    Rather than 

    Public Class Customer
        Public Property CustomerIdentifier() As Object
        Public Property CompanyName() As Object
        Public Property ContactName() As Object
        Public Property ContactTitle() As Object
        Public Property StreetAddress() As Object
        Public Property City() As Object
        Public Property PostalCode() As Object
        Public Property Country() As Object
        Public Property Phone() As Object
        Public Property JoinDate() As Object
        Public Property ActiveStatus() As Object
        Public Overrides Function ToString() As String
            Return $"{CustomerIdentifier} - {CompanyName}"
        End Function
    End Class
    
    

    Going back to the post, this with Option Strict On, Option Infer On

    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New CustomerOperations
    
            ListBox1.DataSource = ops.GetCustomers()
            ListBox1.DisplayMember = "CompanyName"
            AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            If ListBox1.SelectedItem IsNot Nothing Then
                TextBox1.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Field(Of String)("ContactName")
            End If
        End Sub
    End Class

    Option Strict Off, Option Infer On

    Option Strict Off
    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New CustomerOperations
    
            ListBox1.DataSource = ops.GetCustomers()
            ListBox1.DisplayMember = "CompanyName"
            AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            If ListBox1.SelectedItem IsNot Nothing Then
                'TextBox1.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Field(Of String)("ContactName")
                TextBox1.Text = CType(ListBox1.SelectedItem.Item("ContactName"), String)
            End If
        End Sub
    End Class

    With this as the read

    Public Function GetCustomers As DataTable
        Dim dt as new DataTable
    
        mHasException = False
    
        Dim selectStatement As String = 
                <SQL>
                SELECT CustomerIdentifier
                        ,CompanyName
                        ,ContactName
                        ,ContactTitle
                        ,StreetAddress
                        ,City
                        ,PostalCode
                        ,Country
                        ,Phone
                        ,JoinDate
                        ,ActiveStatus
                FROM dbo.Customers
                </SQL>.Value
    
        Using cn = New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd = New SqlCommand With {.Connection = cn}
    
                cmd.CommandText = selectStatement
    
                Try
                    cn.Open()
    
                    dt.Load(cmd.ExecuteReader())
                    dt.Columns("CustomerIdentifier").ColumnMapping = MappingType.Hidden
                Catch ex As Exception
    
                    mHasException = True
                    mLastException = ex
    
                End Try
    
            End Using
        End Using
    
        return dt
    End Function


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, June 5, 2018 12:13 PM
    Moderator
  • Karen,

    What you show I've seen on Internet but it is not strongly typed. It is afaik typed but not strongly typed. 

    If you want to see an example of a strongly typed class you can open in a XSD file the generated theDataset.designer.vb (you have to show all files) or theDatasedesigner.cs inside. 

    In fact it is almost impossible to make by hand.  It is not needed in the generic classes, because there you never use weak identifiers as "Identifier". 

    David Sceppa's (a member of the .Net development team of the first .Net) books where completely based on it (afaik as the dataset design). I assume it was never meant that people would use the not strongly typed dataset.  

    https://www.amazon.com/Books-David-Sceppa/s?ie=UTF8&page=1&rh=n%3A283155%2Cp_27%3ADavid%20Sceppa

     


    Success
    Cor

    Tuesday, June 5, 2018 2:29 PM
  • Karen,

    What you show I've seen on Internet but it is not strongly typed. It is afaik typed but not strongly typed. 

    If you want to see an example of a strongly typed class you can open in a XSD file the generated theDataset.designer.vb (you have to show all files) or theDatasedesigner.cs inside. 

    In fact it is almost impossible to make by hand.  It is not needed in the generic classes, because there you never use weak identifiers as "Identifier". 

    David Sceppa's (a member of the .Net development team of the first .Net) books where completely based on it (afaik as the dataset design). I assume it was never meant that people would use the not strongly typed dataset.  

    https://www.amazon.com/Books-David-Sceppa/s?ie=UTF8&page=1&rh=n%3A283155%2Cp_27%3ADavid%20Sceppa

     


    Success
    Cor

    I disagree, if I have time later then I will respond yet my day is fairly filled.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, June 5, 2018 2:58 PM
    Moderator
  • Hi Cor,

    I don't think you a fool, maybe you a genius of OOP, but as all genius you are not able to explain thinks to people.

    For sure you are not an istructor and I DO NOT undertsnd you at all.

    best regards 

    Claudio

    Sunday, June 10, 2018 11:20 AM
  • Hi Cor,

    I don't think you a fool, maybe you a genius of OOP, but as all genius you are not able to explain thinks to people.

    For sure you are not an istructor and I DO NOT undertsnd you at all.

    best regards 

    Claudio

    I know, I've not seen one message from you where you did not write that you are perfect. You have the habbit that you only read what you want to read and then tell that it is the solution.

    However, I've the habbit not to write in that way. I get than many points but even if you mark 10000 times my replies as answer and vote 100000 times my replies as helpful, I don't do that.

    If I reply in threads you're active in, it is only because these forums are made as a knowledge base and other persons can get the wrong impression of a solution. 


    Success
    Cor


    Sunday, June 10, 2018 1:06 PM
  • this forum is for genius like you and beginners like me.

    So please don't care about me.

    Other people can help me to understand.

    Take care.

    Sunday, June 10, 2018 3:47 PM