How to import csv file in Datagridview with certain columns and rows? - vb.net

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.

Related

How to retrieve actual OleDb table schema (excluding additional table columns)

When I run this code it is also retrieving some other fields which are not present in the table. How can I overcome this?
Dim conn As New OleDb.OleDbConnection
'Create a connection string for an Access database
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\check\a.mdb"
'Attach the connection string to the connection object
conn.ConnectionString = strConnectionString
'Open the connection
conn.Open()
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
ComboBox1.Items.Add(TableRow.Item("COLUMN_NAME"))
The additional columns which is also retrieved are:
1.ID
2.Date create
3.Date update
4.Id
5.Lv
6.Name
7.parent Id
8.Type
9.GUID
10.Id
... and 6 more. The original schema consists of only 5 fields.
Your problem is simply that the variable selected has the value Nothing when you insert it into the Restrictions() array. When I run the following code I only get the column names for the table named [new]:
Option Strict On
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim connStr As String =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\test\so34490626\a.mdb"
Using conn As New OleDbConnection(connStr)
conn.Open()
Dim selected As String = "new"
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
Console.WriteLine(TableRow.Item("COLUMN_NAME"))
Next
End Using
End Sub
End Module
The result is:
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
However, when the value of selected is Nothing ...
Dim selected As String = Nothing
... I get the "extra" columns you describe
DateCreate
DateUpdate
Id
Lv
Name
ParentId
Type
Attributes
DataType
FieldName
IndexType
SkipColumn
SpecID
Start
Width
DateDelim
DateFourDigitYear
DateLeadingZeros
DateOrder
DecimalPoint
FieldSeparator
FileType
SpecID
SpecName
SpecType
StartRow
TextDelim
TimeDelim
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
The reason is revealed if I change the Console.WriteLine to include the table names:
Console.WriteLine("[{0}].[{1}]", TableRow.Item("TABLE_NAME"), TableRow.Item("COLUMN_NAME"))
Then we see:
[MSysAccessStorage].[DateCreate]
[MSysAccessStorage].[DateUpdate]
[MSysAccessStorage].[Id]
[MSysAccessStorage].[Lv]
[MSysAccessStorage].[Name]
[MSysAccessStorage].[ParentId]
[MSysAccessStorage].[Type]
[MSysIMEXColumns].[Attributes]
[MSysIMEXColumns].[DataType]
[MSysIMEXColumns].[FieldName]
[MSysIMEXColumns].[IndexType]
[MSysIMEXColumns].[SkipColumn]
[MSysIMEXColumns].[SpecID]
[MSysIMEXColumns].[Start]
[MSysIMEXColumns].[Width]
[MSysIMEXSpecs].[DateDelim]
[MSysIMEXSpecs].[DateFourDigitYear]
[MSysIMEXSpecs].[DateLeadingZeros]
[MSysIMEXSpecs].[DateOrder]
[MSysIMEXSpecs].[DecimalPoint]
[MSysIMEXSpecs].[FieldSeparator]
[MSysIMEXSpecs].[FileType]
[MSysIMEXSpecs].[SpecID]
[MSysIMEXSpecs].[SpecName]
[MSysIMEXSpecs].[SpecType]
[MSysIMEXSpecs].[StartRow]
[MSysIMEXSpecs].[TextDelim]
[MSysIMEXSpecs].[TimeDelim]
[new].[GENDER]
[new].[MEMBER OF RISHI PRASAD]
[new].[NAME OF SADHAK]
[new].[PROFESSION]
The "MSys*" tables are system tables that are hidden by default in the Access user interface.
Before looping on your table rows, you need to identify the valid/permanent columns of your dataTable.
To do so, you should first browse the columns collection of your datatable object. By checking the properties of each one of these columns, you will be able to identify the temporary ones. I guess it might be hidden somewhere in the 'extended properties' of the DataColumn object.
In order to identify the right property, you will go through something like this (written on the fly ...):
For each tableColumn as DataColumn in dt.Columns
Console.WriteLine(tableColumn.[propertyName].ToString())
...
Next
I do not know exactly which one of the properties will let you know if the column is part of the original table fields. You will have to guess and test in order to find it. Once it's identified, you then know how to select the rows to be added to your combobox.

Retrieve actual Table schema (excluding addtional table schema)In vb.net [duplicate]

When I run this code it is also retrieving some other fields which are not present in the table. How can I overcome this?
Dim conn As New OleDb.OleDbConnection
'Create a connection string for an Access database
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\check\a.mdb"
'Attach the connection string to the connection object
conn.ConnectionString = strConnectionString
'Open the connection
conn.Open()
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
ComboBox1.Items.Add(TableRow.Item("COLUMN_NAME"))
The additional columns which is also retrieved are:
1.ID
2.Date create
3.Date update
4.Id
5.Lv
6.Name
7.parent Id
8.Type
9.GUID
10.Id
... and 6 more. The original schema consists of only 5 fields.
Your problem is simply that the variable selected has the value Nothing when you insert it into the Restrictions() array. When I run the following code I only get the column names for the table named [new]:
Option Strict On
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim connStr As String =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\test\so34490626\a.mdb"
Using conn As New OleDbConnection(connStr)
conn.Open()
Dim selected As String = "new"
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
Console.WriteLine(TableRow.Item("COLUMN_NAME"))
Next
End Using
End Sub
End Module
The result is:
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
However, when the value of selected is Nothing ...
Dim selected As String = Nothing
... I get the "extra" columns you describe
DateCreate
DateUpdate
Id
Lv
Name
ParentId
Type
Attributes
DataType
FieldName
IndexType
SkipColumn
SpecID
Start
Width
DateDelim
DateFourDigitYear
DateLeadingZeros
DateOrder
DecimalPoint
FieldSeparator
FileType
SpecID
SpecName
SpecType
StartRow
TextDelim
TimeDelim
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
The reason is revealed if I change the Console.WriteLine to include the table names:
Console.WriteLine("[{0}].[{1}]", TableRow.Item("TABLE_NAME"), TableRow.Item("COLUMN_NAME"))
Then we see:
[MSysAccessStorage].[DateCreate]
[MSysAccessStorage].[DateUpdate]
[MSysAccessStorage].[Id]
[MSysAccessStorage].[Lv]
[MSysAccessStorage].[Name]
[MSysAccessStorage].[ParentId]
[MSysAccessStorage].[Type]
[MSysIMEXColumns].[Attributes]
[MSysIMEXColumns].[DataType]
[MSysIMEXColumns].[FieldName]
[MSysIMEXColumns].[IndexType]
[MSysIMEXColumns].[SkipColumn]
[MSysIMEXColumns].[SpecID]
[MSysIMEXColumns].[Start]
[MSysIMEXColumns].[Width]
[MSysIMEXSpecs].[DateDelim]
[MSysIMEXSpecs].[DateFourDigitYear]
[MSysIMEXSpecs].[DateLeadingZeros]
[MSysIMEXSpecs].[DateOrder]
[MSysIMEXSpecs].[DecimalPoint]
[MSysIMEXSpecs].[FieldSeparator]
[MSysIMEXSpecs].[FileType]
[MSysIMEXSpecs].[SpecID]
[MSysIMEXSpecs].[SpecName]
[MSysIMEXSpecs].[SpecType]
[MSysIMEXSpecs].[StartRow]
[MSysIMEXSpecs].[TextDelim]
[MSysIMEXSpecs].[TimeDelim]
[new].[GENDER]
[new].[MEMBER OF RISHI PRASAD]
[new].[NAME OF SADHAK]
[new].[PROFESSION]
The "MSys*" tables are system tables that are hidden by default in the Access user interface.
Before looping on your table rows, you need to identify the valid/permanent columns of your dataTable.
To do so, you should first browse the columns collection of your datatable object. By checking the properties of each one of these columns, you will be able to identify the temporary ones. I guess it might be hidden somewhere in the 'extended properties' of the DataColumn object.
In order to identify the right property, you will go through something like this (written on the fly ...):
For each tableColumn as DataColumn in dt.Columns
Console.WriteLine(tableColumn.[propertyName].ToString())
...
Next
I do not know exactly which one of the properties will let you know if the column is part of the original table fields. You will have to guess and test in order to find it. Once it's identified, you then know how to select the rows to be added to your combobox.

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 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!

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