iteration through TableAdapter of a strongly typed DataSet - vb.net

We would like to use a For-Next loop to iterate through a TableAdapter row by row and extract the value of a column in each row from a strongly typed DataSet.
The TableAdapter was created in the Visual Studio DataSet designer. The following names have been used for the database objects.
DataSet Name: DataSetSchedules
DataTable Name: DataTableSchedules
TableAdapter Name: DataTableDataAdapterSchedules
This is the coding I have started:
Dim strClassName As String = ""
Dim objAadapter As New DataSetSchedulesTableAdapters.DataTableTableAdapterSchedules
Dim objDataTable As DataSetSchedulesTableAdapters.DataTableTableAdapterSchedules
<I need a way to fill the table with data from> = objAadapter.GetDataByAll(TextBoxSearch)
For Each row As System.Data.DataRow In objDataTable
strClassName = row.ClassName
Next
Please help by supplying the missing coding we will need because I tried using:
Dim objDataTable As DataTableSchedules = objAadapter.GetDataByAll(TextBoxSearch)
and this error was shown:
Error 1 Type 'DataTableSchedules' is not defined.
I realize that I can set up a command object and DataReader but prefer to use objects that are already existing instead. This one has had us stuck for several days now.

If you type DataSetSchedulesTableAdapters.DataTableTableAdapterSchedules is the data retrieving part, you will also have a class called DataSetSchedules that will have the class structure that will hold the data you retrieve and the strongly typed datatables and datarows.
Dim strClassName As String = ""
Dim objAadapter As New Knowledge_Academy.DataSetSchedulesTableAdapters.DataTableTableAdapterSchedules
Dim objDataTable As Knowledge_Academy.DataSetSchedules.DataSetSchedulesDataTable
Dim objDataRow As Knowledge_Academy.DataSetSchedules.DataSetSchedulesRow
objDataTable = objAadapter.GetDataByAll(TextBoxSearch)
For Each objDataRow In objDataTable.Rows
strClassName = objDataRow.ClassName
Next
I am kind of guessing on some of this, but it should be very close.

Related

How to Select Rows in a Datatable?

How can I use the Variable Itmnmbr instead of hard-coding its value, 'i-2051'?
Dim fr() As DataRow
Dim Itmnmbr As string = "i-2051"
fr = dt.Select("item = 'i-2051'")
The most direct way is to use an Interpolated String, which are available from Visual Studio 2015, VB.Net 14:
Dim Itmnmbr As string = "i-2051"
fr = dt.Select($"item = '{Itmnmbr}'")
As a suggestion, let's change the names of Variables / Fields so it's easier to read them and also understand what these objects are used for. For example:
Dim dt as New DataTable()
'[...]
Dim itemNunmber As string = "i-2051"
Dim filteredRows As DataRow() = dt.Select(...)
itemNunmber is easier to read than Itmnmbr and filteredRows is more explicit than fr. There are some convetions that most are used to, as dt for DataTable, ds for DataSet etc., in this context. Better be sure that when you read your code after some time you don't get mad with yourself :)
Note that an Interpolated String is the same as a string formatted with String.Format(), so these two are actually the same thing:
Dim filteredRows As DataRow() = dt.Select($"item = '{itemNumber}'")
Dim filteredRows As DataRow() = dt.Select(String.Format("item = '{0}'", itemNumber))
Setting Option Infer On (should be On already), to make use of local type inference, you can write:
Dim filteredRows = dt.Select($"item = '{itemNumber}'")
and let the compiler infer the Type. In Visual Studio, if you move the mouse pointer over the variable, it will tell you what Type that is.
You have other options, if you need more dynamic selections.
The DataTableExtensions (which require a Project Reference to the System.Data.DataSetExtensions assembly - usually already linked along with System.Data), let you use the the AsEnumerable() method.
In LINQ to Objects style:
Here, using the default string Comparer
Dim filteredRows =
dt.AsEnumerable().Where(Function(dr) dr("item").ToString().Equals(itemNumber))
Or in LINQ to SQL style:
Here, using the InvariantCulture for the comparison.
Dim filteredRows =
From row In dt.AsEnumerable()
Where row.Field(Of String)("item").Equals(itemNumber, StringComparison.InvariantCulture)
Select row
See also: StringComparison and Best practices for comparing strings in .NET
These two last methods don't return an array of DataRow objects references, but a EnumerableRowCollection. The advantage is (when you can make use of it) that the collection is returned only when you actually use it (the execution is deferred).
When used correctly, it can improve the performance of your code. Try it out.
Instead of DataTable.Select(), you could also filter your DataTable, using its DefaultView.RowFilter property.
dt.DefaultView.RowFilter = $"item = '{itemNumber}'"
' You can save the filter to restore it later, if needed
Dim previousFilter = dt.DefaultView.RowFilter
When you present the Rows of your DataTable, only the Rows that meet the criteria defined by the Filter are shown (e.g., in a DataGrid of sort).
As mentioned, you're working with References here. The Collection of Rows returned by DataTable.Select() contain references of the Rows in the DataTable.
For example, if you consider the Collection and the filtered DataTable:
Dim filteredRows = dt.Select($"item = '{itemNumber}'")
dt.DefaultView.RowFilter = $"item = '{itemNumber}'"
Assume that filteredRows contains a single Row. Then you apply a Filter.
If you now change the value of filteredRows(0)("item"):
filteredRows(0)("item") = "Some other value"
when you present your DataTable in a UI, no Rows will be shown, since the Filter is active and now none of the Rows meet the filter's criteria: setting filteredRows(0)("item") has changed the value of the Row it refers to.
To remove a Filter, set it to string.Empty:
dt.DefaultView.RowFilter = Sting.Empty
To restore the previously saved filter:
dt.DefaultView.RowFilter = previousFilter

Using the New List command with a Passed Parameter

I'm trying to Pass a Field Parameter from my form textbox to a Function to create a New List object from the Data Table parameter I'm passing.
In the following code, the first tmpReadTable shows with no syntax error, but when I try to use the Parm with the Datatable name I'm not sure what I'm missing syntax wise. I'm new to this, thanks in advance!
Updated code below:
Thank you for all the helpful replies...sorry I'm not more experienced, I'm coming from a Visual Foxpro background.
To summarize:
I want to pass in my IMPORT table parameters from my form.
The cImportTable is an empty SQL Table to use to import and validate each CSV file row.
I found this example in Murach's VB book but he leaves out how the LIST is being created from a PRODUCTS table in an earlier exercise. So I thought I could just substitute my passed cImportTable to do the same...that's where I'm stuck and maybe you all know of a better way.
Private Function ReadImportFile(ByVal cImportFile As String, ByVal cGroupID As String, ByVal cControlTable As String, ByVal cImportTable As String)
MessageBox.Show(cImportFile + " " + cGroupID + " " + cControlTable)
If Not File.Exists(cImportFile) Then
MessageBox.Show("File: " + cImportFile + " does not exist - cancelling process.")
Return False
End If
Dim curFileStream As New StreamReader(New FileStream(cImportFile, FileMode.Open, FileAccess.Read))
Dim curImportTable = "NewDataSet." + cImportTable
'Here I'm trying to create a LIST or DATASET using my Empty SQL Import Table and read in each row of the CSV file in the DO WHILE loop
'...I'm coming from Visual Foxpro background so am not sure what I'm missing or what is the standard procedure to do this simple task.
'This line gives me a syntax issue - and I'm not even sure what it's suppose to do, I'm taking it from Murach's VB book example,
'but he leaves out this vital piece of how to create this LIST from a Datatable - or if it's even the right method to use.
Dim tmpReadTable = New List(Of curImportTable)
Do While curFileStream.Peek <> -1
Dim row As String = curFileStream.ReadLine
Dim columns() As String = row.Split(",")
Dim ImportRecord As New curImportTable
ImportRecord.GroupId = columns(0)
ImportRecord.MemberId = columns(1)
Loop
'More Processing after Importing CSV file.....
curFileStream.Close()
'If lNoErrors
Return True
End Function
You are using a variable instead of TYPE on the code line #3 here
' This seems to be ok, no syntax error
Dim tmpReadTable = New List(Of NewDataSet.FO_ImportDataTable)
' The variable below implicitely will be of STRING type
Dim curImportTable = "NewDataSet." + cImportTable.ToString
' This line is not going to work
Dim tmpReadTable = New List(Of curImportTable)
' BUT THIS WILL
Dim x = New List(Of String)
Another issue is that Dim tmpReadTable happened twice in your code! can't re-declare variable. On top you declared it as NewDataSet.FO_ImportDataTable
Besides, I recommend declare all variables like Dim curImportTable as String, this way you can recognize types easier. Option Infer is good when you use anonymous types, LINQ, etc

Can you populate a Dataset with User Input?

I need to store user input (entered from the console) to a Dataset in Visual Basic. Is this possible? I can't seem to find any information online about doing so. If anyone can point me in the right direction, that would be awesome!
EDIT: The columns in my table are FirstName, LastName, State, etc. in a table named Person.
The start of the application for the console: "Enter FirstName: ", then "EnterLastName: " then etc.
The values for the user inputs are stored in there specific variables eg. firstName, lastName, so I want to know how I can put those variables in a dataset.
Thank you.
Here is a short and basic example. Most likely it will not directly work for what you need as you will probably want to use a typed dataset among other things. Since your question does not specify a question regarding the code you may have already tried, this all I am going to provide.
Option Strict On
Module Module1
Sub Main()
Dim ds As DataSet = CreateNewDataSet()
Dim entries As New List(Of String())
For i = 1 To 3
Console.WriteLine($"Enter first column value for row {i.ToString}:")
Dim input1 As String = Console.ReadLine()
Console.WriteLine($"Enter second column value for row {i.ToString}:")
Dim input2 As String = Console.ReadLine()
entries.Add({input1, input2})
Next
entries.ForEach(Sub(x) ds.Tables(0).Rows.Add(x))
End Sub
Private Function CreateNewDataSet() As DataSet
Dim ds As New DataSet()
Dim dt As New DataTable()
Dim col1 As New DataColumn("Column1")
Dim col2 As New DataColumn("Column2")
dt.Columns.AddRange({col1, col2})
ds.Tables.Add(dt)
Return ds
End Function
End Module
If you don't know column names, you can use reflection to get names of properties of input objects. You can also use attributes to filter properties. Use DataTable.LoadDataRow method to load an array as row.
here is an example to how to do it dynamically:
Dim input As New List(Of Object)
For i = 0 To 5
Console.WriteLine("enter your first name and last name:")
input.Add(New With {.First = Console.ReadLine, .Last = Console.ReadLine})
Next
Dim myData As New DataSet
Dim table = myData.Tables.Add()
table.Columns.AddRange(input.First.GetType.GetProperties.Select(Function(p) New DataColumn(p.Name)).ToArray)
input.ForEach(Function(o) table.LoadDataRow(o.GetType.GetProperties.Select(Function(p) p.GetValue(o, Nothing)).ToArray, False))
For Each row In table.Rows
Console.WriteLine("first:{0} ,Last:{1}", row(0), row(1))
Next

how to increase datatable's name number in vb.net

I know, how to increase integer, string by for statement
but I want know how to change the name by 'for ~next' statement.
For example,
Dim row_sort1 As DataTable = rows1.CopyToDataTable
Dim row_sort2 As DataTable = rows2.CopyToDataTable
Dim row_sort3 As DataTable = rows3.CopyToDataTable
Dim row_sort4 As DataTable = rows4.CopyToDataTable
Dim row_sort5 As DataTable = rows5.CopyToDataTable
Dim row_sort6 As DataTable = rows6.CopyToDataTable
Dim row_sort7 As DataTable = rows7.CopyToDataTable
I had coding like this,, bad cording So I want change by 'for ~next' statement.
I want increase the datatable name's number (1~7)
how can reflect in this coding. I want fix my coding more simple and useful.
I need your help
thank you
I assume you have a Collection of Rows which is your master where you want to copy from.
I have a similiar approach like OSKM. Better use a list collection than an array.
To access tables afterwards in the collection you can use Linq.
' Given master rowcollection
Dim masterRow As EnumerableRowCollection(Of DataRow)
' Empty table collection
Dim tableList As New List(Of DataTable)
For t As Integer = 0 To 6
' copy Master to a new table
Dim newTable As DataTable = masterRow.CopyToDataTable()
' give the new table a name
newTable.TableName = "Table" & t.ToString
' Add new table to collection
tableList.Add(newTable)
Next
' Access a certain table (i.e. Table5) using Linq
Dim table5 As DataTable = tableList.FirstOrDefault(Function(x) x.TableName = "Table5")
If i understand your question correct the following might help.
'Note your datatables will be named Datatable0 to Datatable6
Dim DTs(6) As DataTable
For i = 0 To 6
DTs(i) = New DataTable
DTs(i).TableName = "Datatable" & i
Next
There is probably better ways but this will work!

Visual Basic beginner bugs

I am having trouble with a piece of sample code I am using in a Visual Basic project.
This is the sample:
Dim dataRow As DataRow
dataRow = dataSet.Tables(0).NewRow()
I am getting a NullReferenceException on the second line of the sample when I run it.
Any help is greatly appreciated!!!
The most likely explanation is that there is no table at index 0. It may also be that the datSet itself is null.
Not certain as to what the intent of the code is, but from the looks of it you are trying to add a new row to a dataset? If that is the case, you would need declare a new data row and add it to the dataset. Alternatively you should be able to add a row to the dataset and then set datarow to the new row index.
A DataSet is a collection of DataTables. I'm guessing that the DataTable reference has not yet been established and is not pointing to a DataTable object. Check whether the DataTable reference is null (Nothing in VB.NET) and if so, create a new DataTable object and add some columns to it. Then you will be able to add a new row as the DataTable reference will be pointing to a DataTable object that rows can be added to:
If IsNothing(dataset) = True Then
dataset = New DataSet
dataset.Tables.Add("Table1")
End If
If IsNothing(dataSet.Tables(0)) = True Then
dataSet.Tables(0) = New DataTable
dataSet.Tables(0).Columns.Add("FirstName", GetType(String))
dataSet.Tables(0).Columns.Add("Surname", GetType(String))
dataSet.Tables(0).Columns.Add("DateOfBirth", GetType(DateTime))
End If
Dim dataRow As DataRow = dataSet.Tables(0).NewRow
dataRow.Item("FirstName") = "John"
dataRow.Item("Surname") = "Smith"
dataRow.Item("DateOfBirth") = #11/30/1998#
dataSet.Tables(0).Rows.Add(dataRow)