Array to DataGridView

  • 14 years ago

    Hi,

    I want to fill a datagridview with the data in one array, something like this:

    Public Class User2

     

        Public Sub SetTables()

            Try

                Dim tables As String() = {"Customers", "Items", "Transactions", "Users"}

                DataGridView1.DataSource = tables

            Catch ex As Exception

     

            End Try

        End Sub

     

        Private Sub User2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            Call SetTables()

        End Sub

    End Class

     

    But this doesn’t work. One day I was searching somewhere and I found a lot of documentations about this but know that I need it I can’t find any.

     

    Any help with code samples please.

     

  • 14 years ago
    Each column in your grid has to correspond to a property descriptor in the bound array.  The Strings you have put in the array have no property that returns the string value they contain so it cannot be displayed in the grid.  The previous suggestion will work because the DataTable has a property descriptor for each column.  You could also use something like this:
    Private Structure StringObject

    Private _value As String

    Public Property Value() As String
    Get
    Return Me._value
    End Get
    Set(ByVal value As String)
    Me._value = value
    End Set
    End Property

    Public Sub New(ByVal value As String)
    Me._value = value
    End Sub

    End Structure

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim tables As StringObject() = {New StringObject("Customers"), _
    New StringObject("Items"), _
    New StringObject("Transactions"), _
    New StringObject("Users")}

    DataGridView1.DataSource = tables
    End Sub

























    Note that the StringObject type has a Value property that returns the string value the object contains.  This means that the array will have a corresponding property descriptor, thus that can be bound to a column in the grid.

  • 14 years ago

    Thanks for the help.

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”