How to assign a String variable to a dataset? - sql-server

I read rows from a file, do a check on the first row and then I have to write the next rows of the file into a table called "TestTable" with a method that works on DataSet. It tells me that I can't insert the string type in DataSet.
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "Z:\FitalogItalia\KMaster\SPEKM" 'ATTENZIONE CAMBIARE IN "C:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
Dim objReader As New StreamReader(openFileDialog1.FileName)
Dim ControlLine As String = ""
Dim sLine As String = ""
Dim arrText As New ArrayList()
ControlLine = objReader.ReadLine
If (ControlLine.Contains("H06") And ControlLine.Contains("SPEKM")) Then
sLine = objReader.ReadLine
Dim indice As Integer = 0
Do
If Not sLine Is Nothing Then
arrText.Add(sLine)
DB_SQL.SetDBfromDataset("INSERT INTO TestTable (riga) VALUES (" + arrText.Item(indice) + ");", "TestTable")
indice = +1
End If
Loop Until objReader.ReadLine.Count - 1
End If
objReader.Close()
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
UPDATE I ADDED THE FUNCTION WITH WHICH I LOAD THE DATA ON THE DB. THE PROBLEM IS THE ARRAY LIST BECAUSE I NEED TO PASS A DATASET
Public Function SetDBfromDataset(ByVal ds As Data.DataSet, ByVal TN As String) As Integer
DBadapter.InsertCommand = New SqlCommand
TmpSQLstring = "INSERT INTO " & TN
' ottengo la lista dei campi
ListFields = " ("
For Each myCol In ds.Tables(0).Columns
If (Not IsPrimaryCol(myCol, PKcols)) And (NormalizeDataTypeToDBtype(myCol) <> SqlDbType.Timestamp) Then
ListFields = ListFields & Trim(myCol.ColumnName)
ListFields = ListFields & ","
End If
Next
ListFields = Mid$(ListFields, 1, Len(ListFields) - 1) & ")"
'ottengo la lista dei parametri
ListParam = " VALUES ("
For Each myCol In ds.Tables(0).Columns
If (Not IsPrimaryCol(myCol, PKcols)) And (NormalizeDataTypeToDBtype(myCol) <> SqlDbType.Timestamp) Then
ListParam = ListParam & "#" & Trim(myCol.ColumnName)
ListParam = ListParam & ","
DBadapter.InsertCommand.Parameters.Add(New SqlParameter("#" & Trim(myCol.ColumnName), NormalizeDataTypeToDBtype(myCol)))
DBadapter.InsertCommand.Parameters("#" & Trim(myCol.ColumnName)).SourceColumn = Trim(myCol.ColumnName)
End If
Next
ListParam = Mid$(ListParam, 1, Len(ListParam) - 1) & ")"
DBadapter.InsertCommand.CommandText = TmpSQLstring & ListFields & ListParam
DBadapter.InsertCommand.Connection = CType(DBadapter.SelectCommand.Connection, SqlConnection)
End Function

Streams need to be disposed by calling Dispose or placing in a Using block. This is a text file so you don't even need a stream.
ArrayList is around for backward compatibility but you shouldn't be used in new code. See https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=net-5.0#remarks A good replacement is List(Of T)
I have broken the code into 3 methods. You are doing too many separate tasks in a single method. I have used System.IO.File class to read the file. ReadAllLines returns an array of the lines in the file. Then a simple For Each loop to identify the lines you want to add to the database. I used a List(Of String) to collect the lines. Then pass the list to the database code in InsertText.
Only the value of the parameter changes in the loop.
Private Sub OPCode()
Dim FilePath = GetFilePath()
If FilePath Is Nothing Then
MessageBox.Show("No file selected.")
End If
Dim lst As New List(Of String)
Dim lines = File.ReadAllLines(FilePath)
For Each line In lines
If line.Contains("H06") AndAlso line.Contains("SPEKM")) Then
lst.Add(line)
End If
Next
InsertText(lst)
End Sub
Private Function GetFilePath() As String
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "Z:\FitalogItalia\KMaster\SPEKM" 'ATTENZIONE CAMBIARE IN "C:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Return openFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Sub InsertText(lst As List(Of String))
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("INSERT INTO TestTable (riga) VALUES (#riga);", cn)
cmd.Parameters.Add("#riga", SqlDbType.NVarChar)
cn.Open()
For Each line In lst
cmd.Parameters("#riga").Value = line
cmd.ExecuteNonQuery()
Next
End Using 'closes the connection and disposes the command and the connection
End Sub

Related

Importing PDF into MS SQL

I'm sorry for the log post but I am about to pull my hair out. I am attempting to import a PDF into a database.
The main error I am getting is: "Implicit conversion from data type varchar to varbinary(MAX) is not allowed. Use the CONVERT function to run this query."
Some of the coding included below is for a SEARCH function that is not yet completed. Please disregard that area of coding.
Basically I am loading a PDF in the AxAcroPDF1 box. This works great. It then pre-fills out a few of the textboxes. User inputs the Broker Load Number than hits save and a openfiledialog opens and the file is chosen to be imported. This then is where the failed import happens and the error above is given. I have tried many different avenues but always ending up with the same result. I am at a complete and total loss.
Table structure is as follows:
ID, int, NOT NULL IDENTITY(1,1) PRIMARY KEY,
BROKER_LOAD_NUMBER nvarchar(15) NOT NULL,
PDF_FILENAME,nvarchar(50) NOT NULL,
PETS_LOAD_NUMBER nvarchar(10) NOT NULL,
PAPERWORK varbinary(MAX) NOT NULL
My FULL code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
End Sub
Private Sub btnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
Private Sub SearchResult()
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
'SQL to get specific data from the Documents_Table
cmd.Parameters.Clear()
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
End Sub
Private Sub LbllSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
Dim Extension As String = Path.GetExtension(sFileToUpload)
upLoadImageOrFile(sFileToUpload, "PDF")
upLoadImageOrFile(sFileToUpload, Extension)
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf');"
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", data)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub upLoadImageOrFile(sFilePath As String, sFileType As String)
Dim cmd As New SqlCommand
Dim Data As Byte()
Dim sFileName As String
Dim qry As String
Try
'Read Image Bytes into a byte array
Data = ReadFile(sFilePath)
sFileName = Path.GetFileName(sFilePath)
'Set insert query
qry = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, PAPERWORK)
VALUES ('#bl', '#fn', '#pl', '#pdf')"
'Initialize SqlCommand object for insert.
cmd = New SqlCommand(qry, cmd.Connection)
'We are passing File Name and Image byte data as sql parameters.
cmd.Parameters.AddWithValue("#fn", tbFileName.Text)
cmd.Parameters.AddWithValue("#p1", tbPetsLoadNumber.Text)
cmd.Parameters.AddWithValue("#bl", tbBrokerLoadNumber.Text)
cmd.Parameters.AddWithValue("#fp", tbFilePath.Text)
cmd.Parameters.AddWithValue("#pdf", Data)
cmd.ExecuteNonQuery()
MessageBox.Show("File uploaded successfully")
Catch ex As Exception
MessageBox.Show("File could not uploaded")
End Try
End Sub
Private Function ReadFile(sFilePath As String) As Byte()
Throw New NotImplementedException()
End Function
End Class

error in code vb.net import data from access to sdf

enter image description hereI am using a SQL Server Compact 3.5 database file (.sdf) in vb.net
There was an error parsing the query. [Token line number,Token line offset,,Token in error,,]
Dim flag As Boolean
Dim flag2 As Boolean
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|"
Me.OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
flag2 = (Me.OpenFileDialog1.ShowDialog() = DialogResult.OK)
If flag2 Then
flag = (Operators.CompareString(FileSystem.Dir(Me.OpenFileDialog1.FileName, FileAttribute.Normal), "", False) <> 0)
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & Me.OpenFileDialog1.FileName
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Using conSQL As OleDbConnection = New OleDbConnection(), conMDB As OleDbConnection = New OleDbConnection()
conSQL.ConnectionString = myConnectionStringSQL
conSQL.Open()
conMDB.ConnectionString = myConnectionStringMDB
conMDB.Open()
Using cmdSQL As OleDbCommand = New OleDbCommand(), cmdMDB As OleDbCommand = New OleDbCommand()
cmdMDB.CommandType = Data.CommandType.Text
cmdMDB.Connection = conMDB
cmdMDB.CommandText = "SELECT * FROM [student]"
Dim daMDB = New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
Dim dt = New Data.DataTable()
daMDB.Fill(dt)
For Each dr As Data.DataRow In dt.Rows
' change row status from "Unchanged" to "Added" so .Update below will insert them
dr.SetAdded()
Next
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.Connection = conSQL
cmdSQL.CommandText = "SELECT * FROM [student]"
Dim daSQL = New System.Data.OleDb.OleDbDataAdapter(cmdSQL)
Dim cbuilderMDB = New OleDbCommandBuilder(daSQL)
cbuilderMDB.QuotePrefix = "["
cbuilderMDB.QuoteSuffix = "]"
daSQL.Update(dt)
End Using
conSQL.Close()
conMDB.Close()
End Using
I got rid of the extra boolean variables flag and flag2 and just tested the values directly.
I divided the Using blocks into 2 blocks so the first group of objects can be closed and disposed before the next group starts their work.
I shortened the code by passing properties directly to the constructors of the objects where possible. DataAdapter and StringBuilder also expose a .Dispose method so I included them in the Using blocks.
daMDB.AcceptChangesDuringFill = False
This line of code allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method) so, the DataTable will be ready to add all the records to the second table without the loop.
I don't believe that student is a reserved word in either database so I removed the square brackets.
Both the .Fill and the .Update methods of the DataAdapter will .Open and .Close the connection if they find the connection closed. If they find it open they will leave it open. So, closing the connection is not necessary. Also the End Using closes and disposes all objects included in the Using portion (first line including commas) of the block.
Private Sub OPCode()
OpenFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
Dim MDBFile As String
If OpenFileDialog1.ShowDialog = DialogResult.OK AndAlso Not String.IsNullOrEmpty(OpenFileDialog1.FileName) Then
MDBFile = OpenFileDialog1.FileName
Else
Exit Sub
End If
Dim myConnectionStringMDB As String = "provider=Microsoft.Ace.OLEDB.12.0;" & "data source=" & MDBFile
Dim myConnectionStringSQL As String = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" & "Data Source=" & Application.StartupPath & "\Archive.sdf"
Dim dt = New Data.DataTable()
Using conMDB As OleDbConnection = New OleDbConnection(myConnectionStringMDB),
cmdMDB As OleDbCommand = New OleDbCommand("SELECT * FROM student", conMDB),
daMDB As New System.Data.OleDb.OleDbDataAdapter(cmdMDB)
daMDB.AcceptChangesDuringFill = False
daMDB.Fill(dt)
End Using
Using conSQL As OleDbConnection = New OleDbConnection(myConnectionStringSQL),
cmdSQL As OleDbCommand = New OleDbCommand("SELECT * FROM student", conSQL),
daSql As New OleDbDataAdapter(cmdSQL),
cbuilderMDB As New OleDbCommandBuilder(daSql)
daSql.Update(dt)
End Using
End Sub

Avoid Duplicate record across columns

I Have a code that will determine if a data is already existing. The problem is, it is still adding even already exists.
Already tried some code that will add and not add if data exists
If txtHostname.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Dim theQuery As String = "SELECT * FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2"
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#Monitor1", txtMonitor1.Text)
cmd1.Parameters.AddWithValue("#Monitor2", txtMonitor2.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Asset ([Monitor1],[Monitor2]) values ('" + txtMonitor1.Text + "','" + txtMonitor2.Text + "')", con2)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = ""
txtMonitor2.Text = ""
End If
End Using
con.Close()
End If
It should be, when I search 1 data in column1 it should detect if data is already exists in column1 and column2. Not just in column1.
Well, if you want to search and return the result about whether Fields exist or not , you should not use OledbReader, also I did notice that reader doesn't Read (Even if it is not even correct to use it in this scenario). You could rather use ExecuteScalar and see if Fields exist or not (>0 or <0).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CMDText As String = ("SELECT COUNT(*) FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2")
Dim Found As Integer
If String.IsNullOrEmpty(txtHostname.Text) Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Using CN As New OleDb.OleDbConnection With {.ConnectionString = "CON_STR"},
Cmd1 As New OleDb.OleDbCommand(CMDText, CN)
CN.Open()
With Cmd1.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Found = Cmd1.ExecuteScalar()
End Using
If Found > 0 Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim CmdText1 As String =
("INSERT INTO Asset (Monitor1,Monitor2) VALUES (#Monitor1 ,#Monitor2)")
Using Cmd As New OleDb.OleDbCommand(CmdText1, CN)
With Cmd.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Cmd.ExecuteNonQuery()
' User does not exist, add them
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = String.Empty
txtMonitor2.Text = String.Empty
Cmd.Parameters.Clear()
End Using
End If
End If
End Sub
In my example Code : "CON_STR" = My ConnectionString that I used to test my Code, as you did not provide any.

Passing variables between subs inside class

This may have been asked and answered several times, but I have been unable to find the answer.
In CbProdukt1_SelectedIndexChanged(), I need the associated value from an array from another sub:
Private Sub CbProdukt1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CbProdukt1.SelectedIndexChanged
With Me.LblEnhed1
.Text = Enhed(CbProdukt1.SelectedIndex)
.Location = New Point(230, 150)
End With
Me.Controls.Add(LblEnhed1)
End Sub
This would be easy enough if Enhed() had been public. But it is not as it is dimensioned and retrieved from Sqlite in another sub:
Dim count As Integer
sql = "SELECT COUNT(varenr) AS varenrcount FROM '" & Varedatabase & "'"
cmd = New SQLiteCommand(sql, conn)
count = cmd.ExecuteScalar
sql = "SELECT * FROM '" & Varedatabase & "'"
cmd = New SQLiteCommand(sql, conn)
reader = cmd.ExecuteReader
Dim a = 0
Dim Varenr(count + 5) As String
Dim Varenavn(count + 5) As String
Dim Enhed(count + 5) As String
While (reader.Read())
Varenr(a) = reader("varenr")
Varenavn(a) = reader("Varenavn")
Enhed(a) = reader("Enhed")
CbProdukt1.Items.Add(varenavn(a))
a += 1
End While
Public declarations are only allowed prior to subs at the top of the class.
So how do I get the Enhed(a) from sub to sub?

How to filter DataGridView and manage it?

I am new to VB.Net and Window Forms. I am doing a filtering on a table, so that the words entered in searching machine can be used to show the infos(row) that are relevant only. I will explain my situation after I showed my codes:
Private Sub findTextBox2_TextChanged(sender As Object, e As EventArgs) Handles findTextBox2.TextChanged
Dim viewPerson As DataView
viewPerson = New DataView(Data.ds.Tables("PersonInfos"))
If Not String.IsNullOrEmpty(Me.findTextBox2.Text) Then
Dim person As String = FilterListBox("PersonInfos", Me.findTextBox2.Text)
viewPerson.RowFilter = "ID in (" & person & ") "
Else
viewPerson.RowFilter = ""
End If
DataGridView2.DataSource = viewPerson
con.Close()
End Sub
After this filtering, all the infos (all the columns) frm the table "PersonInfos" will be showed. If I just want the column of "Last Name", "Age" and "Nationality" from the table (in a .mdb file) be shown only. What should i include in the codes.
I have search online and didn't manage to find a solution to my problem. Any help will be much appreciated. Thank you in advance.
This is what inside the method FilterListBox:
Private Function FilterListBox(ByVal TableName As String, ByVal tbText As String) As String
Dim IDs As String = String.Empty
If tbText.Contains("*") Then
If Not tbText.StartsWith("*") Then
tbText = "^" + tbText
End If
tbText = tbText.Replace("*", ".*")
If tbText.Contains("?") Then
tbText = tbText.Replace("?", ".")
End If
For Each row As DataRow In data.ds.Tables(TableName).Rows
If System.Text.RegularExpressions.Regex.IsMatch(row.Item("Name"), tbText, System.Text.RegularExpressions.RegexOptions.IgnoreCase) Then
If IDs <> "" Then IDs &= ","
IDs &= row.Item("ID")
Dim dfd As String = row.Item("Name").ToString()
Dim a As Boolean = System.Text.RegularExpressions.Regex.IsMatch(row.Item("Name"), tbText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
End If
Next
Else
For Each row As DataRow In data.ds.Tables(TableName).Rows
If row.Item("Name").ToString.StartsWith(tbText, StringComparison.CurrentCultureIgnoreCase) Then
If IDs <> "" Then IDs &= ","
IDs &= row.Item("ID")
Dim dfd As String = row.Item("Name").ToString()
Dim a As Boolean = System.Text.RegularExpressions.Regex.IsMatch(row.Item("Name"), tbText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
End If
Next
End If
If IDs <> "" Then
Return IDs
Else
Return "1=2"
End If
End Function
Try this
Dim viewPerson As DataView
Dim da As New OleDbDataAdapter
Dim tbl as New DataTable
da = New OleDbDataAdapter("SELECT Last Name, Age, Nationality FROM PersonInfos", con)
da.Fill(tbl)
viewPerson = New DataView(tbl)

Resources