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!
Related
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
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.
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.
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.
I'm having a hard time joining 2 datatables and have the joined datatable
as result.
First datatable (labels) holds data including a printerid.
Second datatable (printers) holds printer references (id > unc)
I would like to have as endresult (joined) a datatable with all data
from the first datatable with the field (unc) of the second datatable.
This is what i have been trying: (mind that fixed paths are for convenience...)
Sub Main()
Dim ds1 As new DataSet
ds1.ReadXml("C:\Program Files (x86)\[COMPANY]\ASW2XML\BICOLOR_a07bfc62-501e-4444-9b6e-3b9d3550e1a4.xml")
Dim ds2 As New DataSet
Dim li As string()
li = IO.File.ReadAllLines("C:\Program Files (x86)\[COMPANY]\ASW2XML\printers.dat")
Dim printers As New DataTable("Printers")
printers.Columns.Add("REPRT2")
printers.Columns.Add("REPRT3")
For Each s In li.ToList
Dim dr As DataRow = printers.NewRow
dr.Item(0) = s.Split("=")(0)
dr.Item(1) = s.Split("=")(1)
printers.Rows.Add(dr)
Next
printers.AcceptChanges
Dim labels As DataTable = ds1.Tables(0)
Dim joined As new DataTable("data")
'Dim lnq = From label In labels.AsEnumerable Join printer In printers.AsEnumerable On label("REPRT") Equals printer("REPRT2") Select printer
'Dim lnq = From l In labels Group Join p In printers On l Equals p("REPRT2") Into Group From p In Group Select label = l, ppath = If(p Is Nothing, "(Nothing)", p("REPRT3"))
Dim lnq = labels.AsEnumerable().Where(Function(o)printers.Select("REPRT2 =" & o.Item("REPRT").ToString).Length = 0)
joined = lnq.CopyToDataTable
End Sub
Thx for your help and inspiration!
grtz -S-
Have you tried http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx
Make your datatables as an extension of IEnumerable (like list as you did) and a join in linq would make it work easily.
then send the joined tables to any destination you want.
I thought a comment would be harder to understand so I moved it in a post.
I wrote a bit of strucure that shoud help you understand how Join works:
structure Label
Public printerId as long
Public driver as Strring
end structure
structure Printer
Public unc as string
end structure
If you set Labels and Printers to DataTable (instead of the structures below), you shoud have something like :
function DoJoin() as datatable
'You might remove as datatable in query declaration
dim query as datatable = Labels.Join(Printers, Function(aLabel) aLabel, _
function(aPrinter) aPrinter.unc, _
function(aLabel, aPrinter) New With
{ .printerID = aLabel.printerId, .driver = aLabel.Driver, _
.unc = aPrinter.unc
})
return query
end function
However I wote it this morning in notepad, so you might have to adjust this. I just want to add that you must have the same type of container in order to use join (eg : example in Join at msdn they used 2 Lists.), that are compatible with Linq obects (datatable I do not know).
I decided to do it the "hard" way and loop through all rows in parent table.
This goes very fast for a minor amount of records, I don't know if running this on
a larger amount of records speed will greatly decrease over using a Linq solution...
This is the code that I'm using atm:
Sub Main()
Dim ds As new DataSet
ds.ReadXml("C:\Program Files (x86)\[COMPANY]\ASW2XML\BICOLOR_a07bfc62-501e-4444-9b6e-3b9d3550e1a4.xml")
Dim labels As DataTable = ds.Tables(0)
Dim printers As DataTable = GetPrinters
labels.Columns.Add("REPRT2").SetOrdinal(labels.Columns.IndexOf("REPRT")+1) 'insert new column after key column
labels.CaseSensitive=False
labels.AcceptChanges
For Each dr As DataRow In labels.Rows
Dim p As String = String.Empty
Try
p = printers.Select("ID='" & dr("REPRT") & "'")(0).Item("PATH").ToString
Catch ex As Exception
End Try
dr("REPRT2") = p
Next
labels.AcceptChanges
End Sub
Function GetPrinters As DataTable
Dim printers As New DataTable("Printers")
Dim li As string()
li = IO.File.ReadAllLines("C:\Program Files (x86)\[COMPANY]\ASW2XML\printers.dat")
printers.Columns.Add("ID")
printers.Columns.Add("PATH")
For Each s In li.ToList
Dim dr As DataRow = printers.NewRow
dr.Item(0) = s.Split("=")(0)
dr.Item(1) = s.Split("=")(1)
printers.Rows.Add(dr)
Next
printers.AcceptChanges
Return printers
End Function