How do I read a datarow in a datatable?-VBForums
Results 1 to 2 of 2

Thread: How do I read a datarow in a datatable?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Sep 2016
    Posts
    66

    How do I read a datarow in a datatable?

    I have a datatable and I would like to use a Message box to view data rows periodically, how do i do this?

    the datatable has columns in it that will change from time to time, but i'd like the output to look like this:

    FirstName, LastName, Address, City, State, Zip

    Why doesn't the below work?

    Code:
    MsgBox(datatabel.rows(rownumber).tostring)

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    97,086

    Re: How do I read a datarow in a datatable?

    The code you have there is calling the ToString method on the DataRow. It's a bit presumptuous to assume that that will output a String contain all the row's fields in the format you want. Most complex will simply return the type name when you call ToString, or sometimes the type name and the value of the most-used property. In the case of a DataRow, you have to actually get the values from each field and then use them in whatever way is appropriate in your case. If you want to do that in a way that works regardless of the number and type of columns then you can do this:
    vb.net Code:
    1. Dim table As DataTable
    2.  
    3. '...
    4.  
    5. For Each row In table.AsEnumerable()
    6.     MessageBox.Show(String.Join(", ", row.ItemArray))
    7. Next
    The ItemArray property returns an Object array containing all the field values. If you want code more specific to your data then you can do something like this:
    vb.net Code:
    1. Dim table As DataTable
    2.  
    3. '...
    4.  
    5. For Each row In table.AsEnumerable()
    6.     MessageBox.Show(String.Format("{0}, {1:d}, {2:c}",
    7.                                   row("Name"),
    8.                                   row("DateOfPurchase"),
    9.                                   row("Cost")))
    10. Next
    By specifying the columns you want by name or index, you can ignore some columns and also format certain columns in ways other than the default.
    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

Tags for this Thread

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.