Visual Basic beginner bugs - vb.net

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)

Related

Select from a DataTable from a Module

I've got a DataTable in DataSet which is filled on Form's Load event with some data from an SQL database.
I've added a Module where I am creating a function which will utilize the data from the DataTable.
Whilst I am able to get row data from Form's code, I am not able to access it from within the Module which I am guessing has something to do with references to a DataSet/DataTable.
I am typing below from top of my head...
Dim dt as Datatable
Dim dr() as Datarow
Dim DataSet1 as Dataset = New DataSet1
dt = DataSet1.comm_rates
dr = dt.select("fieldName='somevalue'")
Return a = dr(0)("fieldA")
Any help would be much appreciated.
Supposing DataSet1 is inside Class Form1, qualify your reference, e.g
Dim ds1 = Form1.DataSet1
dt = ds1.comm_rates

datatable is empty vb.net

I'm not familiar with .net languages. but I tried to copy a datagridview rows to a datatable.when I use Watch on my datatable it has values but when i try to watch dataset,my datatable is empty. here is my code :
Dim dt As New DataTable("repTable")
For Each col As DataGridViewColumn In dgrMatchesExacutives.Columns
dt.Columns.Add(col.HeaderText)
Next
For Each row As DataGridViewRow In dgrMatchesExacutives.Rows
Dim dRow As DataRow = dt.NewRow()
For Each cell As DataGridViewCell In row.Cells
dRow(cell.ColumnIndex) = cell.Value
Next
dt.Rows.Add(dRow)
Next
If ds.Tables.Contains("repTable") Then
ds.Tables.Remove("repTable")
End If
ds.Tables.Add("repTable")
The Tables property of the DataSet is a DataTableCollection and you add items to this collection using the provided overloads of the Add method. But if you call the overload that receives a string you CREATE a NEW datatable (empty of course). The fact that you call the created datatable with the same name of the existing one has no relevance for the dataset.
If you have manually created a datatable and prepared it yourself with a schema and records then you need to use the overload that takes a DataTable
ds.Tables.Add(dt)

How do I sort a datatable

How do I sort a datatable? I need to return a datatable from a function. I have been struggling with this for hours, and the internet has a few different answers, none of which seem to work for me.
Edit: I want to punch myself. Do a DataView.Sort on your table, then a DataView.ToTable() to put the sorted data into a new dataset...
Example:
Dim view As New DataView(OriginalDataSet) 'Put your original dataset into a dataview
view.Sort = "ColumnName" ' Sort your data view
Dim NewDataSet As DataTable = view.ToTable() ' Put your dataview into a new datatable
End of example
I have a relatively simple example table below, taken from a teaching website. The one twist is that there are duplicate values in the row I am trying to sort on.
Module Module1
Sub Main()
' Get a DataTable instance from helper function.
Dim table As DataTable = GetTable()
End Sub
''' <summary>
''' Helper function that creates new DataTable.
''' </summary>
Function GetTable() As DataTable
' Create new DataTable instance.
Dim table As New DataTable
' Create four typed columns in the DataTable.
table.Columns.Add("Dosage", GetType(Integer))
table.Columns.Add("Drug", GetType(String))
table.Columns.Add("Patient", GetType(String))
table.Columns.Add("Date", GetType(DateTime))
' Add five rows with those columns filled in the DataTable.
table.Rows.Add(25, "Indocin", "David", DateTime.Now)
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now)
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now)
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now)
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now)
table.Rows.Add(21, "Aspirin", "Janet", DateTime.Now)
Return table
End Function
End Module
I have tried selecting into an array, then looping through the array and putting each row into a new datatable, but the select isn't grabbing rows. Example:
drarray = ds.Select("I want to select all here", "MySortColumn")
I have tried various looping strategies, with inner loops, etc and can't seem to figure that out.
I have tried dataTable.DefaultView.Sort = "sortExp" but I can't get that to work.
So what am I missing? I figure with the DefaultView and Select methods I'm just missing something syntactly.
So what's the best way to go, and what am I missing?
You can use something like this:
Return table.Select("","Columns to sort on").CopyToDataTable
Use a DataView to create a view of your data in the DataTable. This allows you to sort, filter, etc. Here's a C# example: Datatable VS dataview
This may help you sortExp can be field on which based the sort should be performed filterExp that should evaluate to true or false. assuming the following fields
Dim filterExp As String = "Patient<> ''"
Dim sortExp As String = "Date "
dt_item.Select(filterExp, sortExp, DataViewRowState.CurrentRows)
The above code shows how to filter and sort the data table dt_item. The filter expression selects Date whose Patient is not NULL. The sort expression causes the results to be sorted by the Date column

iteration through TableAdapter of a strongly typed DataSet

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.

Copy LINQ results to data set/table

I’m working on a form that has a few data grid views that are populated from LINQ queries, no problem there it works as it should however that sorting does not work. After doing some reading its because LINQ results do not support sorting.
As I have the LINQ results already is there a way of copying the results into a dataset or datatable then binding the data grid view to that so sorting will work?
Thanks
EDIT:
Thanks to everyone for the answers, sadly I'm off on holiday for 2 weeks so cant try out and upvote the correct one. However when I return it will be on the top of my list
You can use the CopyToDataTable extension method for this.
The standard implementation of this method only works over IEnumerable<T> where T is of type DataRow but there is an example on MSDN of making your own extension method which works on anonymous types.
I've actually not used CopyToDataTable, in the past I've created a similar end result by creating a BindingList which supports sorting and then creating an instance of it with the query as the IList in the constructor, but the CopyToDataTable approach looks a lot cleaner to me.
In the end I used bits from each option and a little tweak to get it to work with nullable fields.
First thing is getting the CopyToDataTable function into VB, this is done here
http://msdn.microsoft.com/en-us/library/bb669096.aspx
When I tried this it would fail if the column was nullable so I searched and found a mod to that code that would work. Here it is in full
Public Function ExtendTable(ByVal table As DataTable, ByVal type As Type) As DataTable
For Each f As FieldInfo In type.GetFields()
If (Not _ordinalMap.ContainsKey(f.Name)) Then
Dim dc As DataColumn
dc = If(table.Columns.Contains(f.Name), table.Columns(f.Name), table.Columns.Add(f.Name, f.FieldType))
_ordinalMap.Add(f.Name, dc.Ordinal)
End If
Next f
For Each p As PropertyInfo In type.GetProperties()
If Not _ordinalMap.ContainsKey(p.Name) Then
Dim colType As Type = p.PropertyType
If (colType.IsGenericType) AndAlso (colType.GetGenericTypeDefinition() Is GetType(Nullable(Of ))) Then
colType = colType.GetGenericArguments()(0)
End If
Dim dc As DataColumn = IIf(table.Columns.Contains(p.Name), table.Columns(p.Name), table.Columns.Add(p.Name, colType))
_ordinalMap.Add(p.Name, dc.Ordinal)
End If
Next
Return table
End Function
Upvotes all round as they all would have worked I just took this option as it is neater
In C# I do it thus:
DataTable dt = new DataTable();
dt.Columns.Add("a", Type.GetType("System.String"));
dt.Columns.Add("b", Type.GetType("System.String"));
dt.Columns.Add("c", Type.GetType("System.String"));
dt.Columns.Add("d", Type.GetType("System.String"));
foreach (var row in [linqQueryName] )
{
DataRow destRow = dt.NewRow();
destRow["a"] = row.linqCol1;
destRow["b"] = row.linqCol2;
destRow["c"] = row.linqCol3;
destRow["d"] = row.linqCol4;
dt.Rows.Add(destRow);
}
See the code:
Here testData is the data from LINQ query on a list of Class having ID and Name as properties
Dim dataTable As New DataTable()
dataTable.Columns.Add("ID", GetType(Integer))
dataTable.Columns.Add("Name", GetType(String))
For Each item As var In testData
Dim dataRow As DataRow = dataTable.NewRow()
dataRow("ID") = item.ID
dataRow("Name") = item.Name
dataTable.Rows.Add(dataRow)
Next