datatable is empty vb.net - 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)

Related

How to consolidate data for a row before adding it using Datagridview.rows.add()?

I bumped into this problem because I would like my code to work even though I have added new columns to the source. My code adds a row based on the number of rows of the source. My code lacks the ability to consider the number of columns. Here is my code:
For Each srow As datagridviewrow In mytempDG.Rows
dataGridView1.Rows.Add(srow.Cells(0).Value.tostring, srow.Cells(1).Value.tostring, _
& srow.Cells(2).Value.tostring, srow.Cells(3).Value.tostring,srow.Cells(4).Value.tostring, _
& srow.Cells(5).Value.tostring, srow.Cells(6).Value.tostring)
Next
The code above works okay given that I have 7 columns from tempDG (which is my datasource btw). But what if I have added two more columns (which makes it 9). I would then have to edit the code from the source (add "srow.cells(7).value.tostring, srow.cells(8).value... etc")
I know how to loop through the column but I do not know how to convert it to a data that can be read by rows.add function. This is what I've tried so far:
Dim finrow As List(Of String)
finrow = New List(Of String)
For Each srow As datagridviewrow In mytempDG.Rows
finrow.clear
For Each scol As DataGridViewColumn In mytempDG.Columns
finrow.add(srow.Cells(scol.Index).Value.ToString)
Next
dataGridView1.Rows.Add(finrow)
Next
How can I create a collection of data first before adding it using the rows.add() function? Also may I know what kind of data is needed by rows.add()? I am assuming it is a list of values (in my case, I used List(of String)).
Thank you guys in advance and have a nice day!
You can supply an array of object to the Add method of the DataGridView:
For Each srow As DataGridViewRow In mytempDG.Rows
Dim obj(mytempDG.Columns.Count) as Object
For col as Integer = 0 to mytempDG.Columns.Count - 1
obj(col) = srow.Cells(col).Value.ToString()
Next
dataGridView1.Rows.Add(obj)
Next
I'm assuming myTempDG is a DataGridView, in that case you can cast the rows of the myTempDG to an array of DataGridViewRow and then AddRange:
Dim rows() As DataGridViewRow
rows = myTempDG.Rows.Cast(Of DataGridViewRow)().ToArray
dataGridView1.Rows.AddRange(rows)
OK I GOT IT
Dim numcol As Integer = mytempDG.Columns.count
Dim finrow(numcol) As String
For Each srow As datagridviewrow In mytempDG.Rows
For Each scol As DataGridViewColumn In mytempDG.Columns
finrow(scol.Index) = srow.Cells(scol.Index).Value.ToString
Next
dataGridView1.Rows.Add(finrow)
Next
But it seems a little slow..
This is much better.. after considering to not transfer the dataset to tempDG..
For each xrow as DataRow in ds.Tables(0).Rows
datagridview1.Rows.Add(xrow.ItemArray)
Next

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)

How to import csv file in Datagridview with certain columns and rows?

I'm new to VB.net and I don't know how to display certain columns and rows in datagridview that was imported from CSV file. My problem is I have many columns and all I want to display is 2 columns:
Name,Age,Mobile Number,ID number
Alex,18,09848484841,0010
George,19,02987654321,0020
Toni,17,09277470257,0030
How can I display only the Name & Age columns and its rows?
If you use a datatable you get the data structure and collection together. something like this:
Dim sr As New IO.StreamReader(filename)
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(","c)
dt.Columns.AddRange({New DataColumn(newline(0)), _
New DataColumn(newline(1))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}
dt.Rows.Add(newrow)
End While
DataGridView1.DataSource = dt
Use a custom class with properties that match the data you want to store and make an instance of that class for each row of data use read, then have a List(Of {custom class}) to hold each object and the DGV's DataSource property can view the collection in the grid. The property names in the class will be used as the header.

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.

vb.net working with multiple controls added at runtime

I am adding a tab page and datagridview to a Tab Control for every record in a datatable.
I would like to have a new Tab/DataGridView for each record (there will be ~3 for right now). I am declaring a new DataGridView D. How do I refer to these controls later?
I will want to do things like save changes in the datagridview to the database. Currently I can get the data on the screen and it looks good, but I believe I am not adding the DataGridView controls correctly because I keep re-using "D" as the control.
Dim dt As New DataTable
GetDataTable("SELECT * FROM aFeeTypes DescSeq", dt)
Dim i As Integer
'for each class in the datatable add a tab and a datagridview
For i = 0 To dt.Rows.Count - 1
Dim dr As DataRow
dr = dt.Rows(i)
Dim D = New DataGridView
D.Visible = True
Dim tp As New TabPage
tp.Name = "tp" & i
tp.Text = dr.Item("Desc2")
frmUI.tcFee.TabPages.Add(tp)
frmUI.tcFee.TabPages(i).Controls.Add(D)
dgv_Fill(D, "SELECT * FROM Fee WHERE ClassID=" & dr.Item("ClassID") & " ORDER BY Seq")
D.AutoResizeColumns()
D.Width = tp.Width
D.Height = tp.Height
Next i
this does not work:
With frmUI.Controls("D" & i)
.AutoResizeColumns()
.Width = tp.Width
.Height = tp.Height
End With
D is purely the variable name in the scope you are using it in.
You need to give the control a unique Name that yo can reference it by later.
The Name property can be used at run time to evaluate the object by
name rather than type and programmatic name. Because the Name property
returns a String type, it can be evaluated in case-style logic
statements (Select statement in Visual Basic, switch statement in
Visual C# and Visual C++).
I found a solution to the problem. The problem is that the new row has an autonumber ID.
When da.update(dt) occurs, the new row is inserted to the database. The database knows the new autonumber ID. However, the datatable does not.
For the datatable to know, the dataadapter is refilled. However, this causes the datatable to have all the old rows plus all the new rows and they all appear in the datagridview.
By clearing the old rows from the datatable, the fill refreshes all the data in the datatable and therefore refreshes the datagridview.
Public Sub dgv_AddRow(ByVal dgvName As String)
Dim dgv As DataGridView = colDataGridView.Item(dgvName)
Dim da As SqlDataAdapter = colDataAdapter.Item(dgvName)
Dim dr As DataRow = frmUI.allDataSet.Tables(dgvName).NewRow
'autopopulate the class id
dr("ClassID") = dgv.Parent.Tag
'add the new row
frmUI.allDataSet.Tables(dgvName).Rows.Add(dr)
'get the changed table
Dim dt As DataTable = frmUI.allDataSet.Tables(dgvName)
'inserts the new row to the database. concurrency violation
'will occur because datatable does not know the new Autonumber ID for the new row.
da.Update(dt)
'remove the datatable rows so they can be replaced using the adapter fill
'if rows are not cleared, following fill causes datatable to
'have existing rows plus all the rows again due to the fill
frmUI.allDataSet.Tables(dgvName).Rows.Clear()
'refill the adapter (refill the table)
'Everything you do to the underlying dataTable
'gets displayed instantly on the datagridview
da.Fill(frmUI.allDataSet, dgvName)
End Sub