How to retrieve actual OleDb table schema (excluding additional table columns) - vb.net

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.

Related

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

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.

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 Gridview DataKeys for information display

I am trying to select a row from my gridview and then display further information associated with the data from the row. In order to do this I am setting a DataKey which in this case is ID. I then want to access my database and select all the records where the ID is equal to the ID which is the DataKey of the selected row. I am having a bit of trouble with this unfortunately as I am not aware how to correctly access the DataKey of my Selected row. Below is my code. I am trying to take the value of the datakey and set it as an int, which then in return is used in my SELECT statement.
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim RegDataConn1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("App_Data/1202389.mdb"))
Dim i As Integer = GridView1.SelectedIndex
Dim hotelid As Integer = GridView1.DataKeys(i).Value
Dim cmd1 As OleDbCommand = New OleDbCommand("SELECT * FROM Ratings WHERE Hotel.Hotel_ID=" & hotelid.ToString(), RegDataConn1)
RegDataConn1.Open()
Dim myDA1 As OleDbDataAdapter = New OleDbDataAdapter(cmd1)
Dim myDataSet1 As DataSet = New DataSet
myDA1.Fill(myDataSet1, "Table1")
GVDetailView.DataSource = myDataSet1.Tables("Table1").DefaultView
GVDetailView.DataBind()
RegDataConn1.Close()
End Sub
http://postimg.org/image/yp3ukwsdv/ Here is a picture of my error
Getting the value of the datakey should be:
Dim hotelid As String = GridView1.DataKeys(i).Value.ToString()
Or convert the type to integer if it really is.
What you have missed is to tell the GridView its DataKeyNames.
To do so, change the markup of your gridview into something like:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="hotelid">
</asp:GridView>
Your query string is not dynamic
"SELECT Service_Rating, Price_Rating, Clean_Rating, Location_Rating, Overall_Rating, Text_Review FROM Ratings WHERE Hotel.Hotel_ID=hotelid"
Should be
"SELECT Service_Rating, Price_Rating, Clean_Rating, Location_Rating, Overall_Rating, Text_Review FROM Ratings WHERE Hotel.Hotel_ID=" & hotelid.ToString
Although this may resolve your problem I would recommend using stored procedures, rather than dynamic SQL. Its faster and more secure.

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.