none
Getting Column Name to variable. RRS feed

  • Question

  • I want to input the names of the columns into an array.

                For I = 1 To 20
                    MyText(I) = ""
                Next

    So what I need to know is what is the syntax for adding the name of the table column, as a string, to the array string value.


    gwboolean

    Thursday, March 19, 2020 5:41 PM

Answers

  •         For i = 0 To table.Columns.Count - 1
                MyText(i) = table.Columns(i).ColumnName
            Next


    Success
    Cor

    • Marked as answer by gwboolean Thursday, March 19, 2020 7:21 PM
    Thursday, March 19, 2020 5:56 PM

All replies

  • Hello,

    Why not use a List(Of T) which if needed can be converted to an array or simply use the list rather than an array.

    Not knowing what columns are, suppose they are DataGridView columns. The variables are locally scoped but could be form or class level scoped.

    Dim columnNamesArray As String() = DataGridView1.
            Columns.Cast(Of DataGridViewColumn).
            Select(Function(column) column.Name).
            ToArray()
    
    Dim columnNamesList As List(Of String) = DataGridView1.
            Columns.Cast(Of DataGridViewColumn).
            Select(Function(column) column.Name).
            ToList()

    Form or class level scoped

    Private columnNamesArray As String()

    Then use it in a sub or function.

    columnNamesArray = DataGridView1.
            Columns.Cast(Of DataGridViewColumn).
            Select(Function(column) column.Name).
            ToArray()

    For a class

    Dim propertyInfos = GetType(SomeClass).
            GetProperties(BindingFlags.Public Or BindingFlags.Instance).
            Select(Function(propertyInfo) propertyInfo.Name).
            ToArray()
    
    Array.Sort(propertyInfos)
    For Each pName As String In propertyInfos
        Console.WriteLine(pName)
    Next


    Please remember to mark the replies as answers if they help and unmarked 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.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange



    Thursday, March 19, 2020 5:46 PM
    Moderator
  •         For i = 0 To table.Columns.Count - 1
                MyText(i) = table.Columns(i).ColumnName
            Next


    Success
    Cor

    • Marked as answer by gwboolean Thursday, March 19, 2020 7:21 PM
    Thursday, March 19, 2020 5:56 PM
  • Exactly what I was looking for.  Thanks.

    gwboolean

    Thursday, March 19, 2020 7:22 PM