Results 1 to 3 of 3

Thread: Function that returns a datatable

  1. #1

    Thread Starter
    Junior Member
    Join Date
    May 2011
    Posts
    28

    Post Function that returns a datatable

    When a function returns a datatable, does it just return a pointer to a datatable? I mean is the below example, which method to load a DataGrid would be better (1 or 2)? Are both equally efficient and accepted use of a function and datatable? (using pseudo-code here)

    Code:
    Function GetData() as DataTable
     Dim myDataTable as New DataTable
     cn.Open()
      rSQLReader = cmd.ExecuteReader
      myDataTable.Load(rSQLReader)
     cn.Close()
     Return myDataTable
    End Function
    
    Sub LoadDataGrid1()
     Dim dt as New DataTable
     dt = GetData()
     myDataGrid.DataSource = dt
    End Sub
    
    Sub LoadDataGrid2()
     myDataGrid.DataSource = GetData()
    End Sub

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Function that returns a datatable

    Your first option is wrong. The first line creates a new DataTable object and assigns it to the 'dt' variable. It then discards that object without ever using it and replaces it with the one that was created and returned by the GetData method. The 'New' keyword is NOT part of a declaration. Do not use the 'New' keyword unless you specifically want to create a new object. You obviously don't want to do that here because you are already getting an object from the GetData method. This:
    vb.net Code:
    1. Sub LoadDataGrid1()
    2.  Dim dt As DataTable
    3.  dt = GetData()
    4.  myDataGrid.DataSource = dt
    5. End Sub
    is the drawn-out equivalent of the second option. Note the absence of the 'New' keyword, so a variable is declared but no new object is created or assigned to it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Junior Member
    Join Date
    May 2011
    Posts
    28

    Re: Function that returns a datatable

    Thank you!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width