Visual Basic InputBox closing error - vb.net

This is a bit of a weird question, and apologies for the vast amount of code the question contains, but, I've been given somebody else's project to maintain, and the user has come to me with an error. There is a button which opens the InputBox, seen below.
The form is used to enter a path of a file to import. If the user enters no path, or an incorrect one, an error is displayed - fine. Now, the problem is, is that if the user presses the 'Cancel' button or the x in the top right to close the form, it also returns the same error, saying that the path cannot be found.
After looking through the following code, I can't work out how to make it so that the error is not displayed when pressing the x or Cancel, so can anybody help me out at all?
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Try
Dim importbox As String = InputBox("Input path", "Import", "")
Dim fi As New FileInfo(importbox)
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
Dim conn As New OleDbConnection(connectionString)
conn.Open()
Dim add1 As String = ""
Dim add2 As String = ""
Dim add3 As String = ""
Dim add4 As String = ""
Dim add5 As String = ""
Dim postcode As String = ""
Dim telephone As String = ""
Dim fax As String = ""
Dim email As String = ""
Dim customercode As String = ""
Dim customername As String = ""
Dim webpage As String = ""
Dim mobile As String = ""
Dim headerTable As DataTable = ugHeaders.DataSource
Dim csvArray(headerTable.Rows.Count) As String
Dim i As Integer = 0
For Each dr As DataRow In headerTable.Rows
csvArray(i) = dr.Item("CSVName")
Next
For Each dr As DataRow In headerTable.Rows
Select Case dr.Item("DBName").ToString.Trim
Case "Add1"
add1 = dr.Item("CSVName")
Case "Add2"
add2 = dr.Item("CSVName")
Case "Add3"
add3 = dr.Item("CSVName")
Case "Add4"
add4 = dr.Item("CSVName")
Case "Add5"
add5 = dr.Item("CSVName")
Case "PostCode"
postcode = dr.Item("CSVName")
Case "Telephone"
telephone = dr.Item("CSVName")
Case "Fax"
fax = dr.Item("CSVName")
Case "Email"
email = dr.Item("CSVName")
Case "Customer_Name"
customername = dr.Item("CSVName")
Case "Customer_Code"
customercode = dr.Item("CSVName")
Case "webpage"
webpage = dr.Item("CSVName")
Case "mobile_phone"
mobile = dr.Item("CSVName")
End Select
Next
Dim sqlSelect As String = "SELECT Company, [" & add1 & "], [" & add3 & "], [" & postcode & "], [" & add2 & "], " & _
"[" & telephone & "], [" & fax & "], [" & email & "], [" & customercode & "], " & _
"[" & add4 & "], [" & add5 & "], [" & webpage & "], [" & mobile & "] FROM " & fi.Name
Dim cmdSelect As New OleDbCommand(sqlSelect, conn)
Dim adapter1 As New OleDbDataAdapter(cmdSelect)
Dim ds As New DataSet
adapter1.Fill(ds, "DATA")
pb_progress.Maximum = ds.Tables(0).Rows.Count
pb_progress.Value = 0
For Each dr As DataRow In ds.Tables(0).Rows
Try
Debug.WriteLine(dr.Item(customercode).ToString.Trim)
If dr.Item(customercode).ToString.Trim = "" Then
Dim str As String = dr.Item(customername)
If str.Trim = "" Then Continue For
Dim length As Integer = str.Length
If length < 20 Then
Else
length = 20
End If
str = Replace(str.Substring(0, length), " ", "_").ToUpper
str = Regex.Replace(str, "[^a-zA-Z _&]", "")
Dim found As Boolean = True
Dim loopcount As Integer = 1
Do Until found = False
Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = #ccode"
Dim checkCmd As New OleDb.OleDbCommand(checkSql, con)
checkCmd.Parameters.AddWithValue("#ccode", str)
Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd)
Dim checkDt As New DataTable
checkDa.Fill(checkDt)
If checkDt.Rows.Count <> 0 Then
found = True
str &= CStr(loopcount)
loopcount += 1
Else
found = False
End If
Loop
dr.Item(customercode) = str
Else
Dim found As Boolean = True
Dim loopcount As Integer = 1
Do Until found = False
Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = #ccode"
Dim checkCmd As New OleDb.OleDbCommand(checkSql, con)
checkCmd.Parameters.AddWithValue("#ccode", dr.Item(customercode))
Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd)
Dim checkDt As New DataTable
checkDa.Fill(checkDt)
If checkDt.Rows.Count <> 0 Then
found = True
dr.Item(customercode) &= CStr(loopcount)
loopcount += 1
Else
found = False
End If
Loop
End If
Dim sql As String
sql = "INSERT INTO Customers(Customer_Code, Customer_Name, Contract_Payment_Terms, Aq_Date, Telephone, Fax, Email, Average_Payment_Terms, webpage, mobile_phone) " & _
"VALUES(#ccode, #cname, 30, #01/01/2016#, #ctele, #cfax, #email, 30, #webpage, #mobile);"
Dim cmd As New OleDb.OleDbCommand(sql, con)
With cmd.Parameters
.AddWithValue("#ccode", dr.Item(customercode))
.AddWithValue("#cname", dr.Item(customername))
.AddWithValue("#ctele", dr.Item(telephone).ToString.Truncate(48))
.AddWithValue("#cfax", dr.Item(fax))
.AddWithValue("#email", dr.Item(email))
.AddWithValue("#webpage", dr.Item(webpage))
.AddWithValue("#mobile", dr.Item(mobile))
End With
cmd.ExecuteNonQuery()
sql = "INSERT INTO [Customer_Addresses] (Cust_Code, PostCode, Alias, Add1, Add2, Add3, Add4, Add5) VALUES(#ccode, #pcode, 'Default'" & _
",#add1, #add2, #add3, #add4, #add5);"
cmd = New OleDb.OleDbCommand(sql, con)
With cmd.Parameters
.AddWithValue("#ccode", dr.Item(customercode))
.AddWithValue("#pcdoe", dr.Item(postcode))
.AddWithValue("#add1", dr.Item(add1))
.AddWithValue("#add2", dr.Item(add2))
.AddWithValue("#add3", dr.Item(add3))
.AddWithValue("#add4", dr.Item(add4))
.AddWithValue("#add5", dr.Item(add5))
End With
cmd.ExecuteNonQuery()
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
pb_progress.Increment(1)
Next
MsgBox("Import successful", MsgBoxStyle.OkOnly, "Success")
Catch ex As Exception
errorLog(ex)
End Try
End Sub

Inputbox will always return a String.
If the Users presses "OK" it will return the String put into the TextBox.
If he cancels the box by pressing X or Cancel it returns "".
I would generally not recommend using an Inputbox for getting a filepath. Use an OpenFileDialog instead. If you have the fullpath already in your Clipboard you can just paste it into the Filename-Textboxof the OFD and press enter.
This should get you started:
Dim ofd as new OpenFileDialog()
// Show the File Dialog to the user and detect he pressed OK or Cancelled
if ofd.ShowDialog = Windows.Forms.DialogResult.OK
// Always check, if the file really exists
if IO.File.exists(ofd.FileName)
importbox = ofd.FileName
Else
msgbox("File does not exist")
Exit Sub
End if
Else
Exit Sub
End if

Related

in vb.net error Command text was not set for the command object

I have a program in vb.net where I need data inserted into the database. When I run this code I get an error:
Command text was not set for the command object
Here is the code I have:
Private Sub InsertRelease(strRelease As String, rowInserted As Boolean)
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim objType As String
Dim strUsername, strPassword, strTable, strDatabase, strDsn, strSystem, strNewSql, sqlStr As String
Dim intRecsAffected As Integer
Dim boolRowInserted As Boolean
strDsn = ComboBox1.Text
strSystem = txtSystem.Text
strUsername = txtUser.Text
strPassword = txtPassword.Text
If con.State <> 1 And strUsername <> "" And strPassword <> "" Then
con.Open("{iSeries As ODBC Driver};System=" + strSystem + ";Dsn=" + strDsn + "; Uid=" + strUsername + "; Pwd=" + strPassword + ";")
Else
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
con = Nothing
End If
sqlStr = "insert into jobscopedb.ppusrfs (search_key_uf,DATA_ITEM_UF, NUMERIC_VALUE_UF) values (strRelease,'81 AB',0);"
strNewSql = ""
con.Execute(strNewSql, intRecsAffected)
con.Close()
con = Nothing
boolRowInserted = (intRecsAffected > 0)
If (boolRowInserted) Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
Exit Sub
errH:
MsgBox(Err.Description)
con = Nothing
End Sub
The following demonstrates what your code might look like using ADO.net.
Pass the connection string directly to the constructor of the connection and pass the command text and connection to the constructor of the command. Open the connection and execute the command. ExecuteNonQuery returns rows affected.
Always use parameters to avoid sql injection.
Private Sub InsertRelease(strRelease As String)
Dim intRecsAffected As Integer
Dim strDsn = ComboBox1.Text
Dim strSystem = txtSystem.Text
Dim strUsername = txtUser.Text
Dim strPassword = txtPassword.Text
'Validate Input
If strUsername = "" OrElse strPassword = "" Then
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
Exit Sub
End If
Using con As New OdbcConnection($"{{iSeries As ODBC Driver}};System={strSystem};Dsn={strDsn}; Uid={strUsername}; Pwd={strPassword};"),
cmd As New OdbcCommand("insert into jobscopedb.ppusrfs (search_key_uf, DATA_ITEM_UF, NUMERIC_VALUE_UF) values (#Release,'81 AB',0);", con)
cmd.Parameters.Add("#Release", OdbcType.VarChar).Value = strRelease
con.Open()
intRecsAffected = cmd.ExecuteNonQuery
End Using 'Closes and disposes the connection and command even it there is an error
If intRecsAffected = 1 Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
End Sub

First-chance exception at 0x761EC42D in foo.exe: Microsoft C++ exception: int at memory location 0x003ED1EC

Dim ColNames(7) As String
Dim Values(7) As Object
Dim now As DateTime = DateTime.Now()
ColNames(0) = "Int1"
ColNames(1) = "Int2"
ColNames(2) = "String1"
ColNames(3) = "String2"
ColNames(4) = "String3"
ColNames(5) = "String4"
ColNames(6) = "String5"
ColNames(7) = "String6"
Values(0) = intVar1
Values(1) = intVar2
Values(2) = strVar1
Values(3) = strVar2
Values(4) = strVar3
Values(5) = strVar4
Values(6) = strVar5
Values(7) = strVar6
Dim goodToInsert As Boolean = True
For i As Integer = 0 To 7
If Values(i) = Nothing OrElse Len(Values(i)) = 0 Then
goodToInsert = False
End If
Next
If goodToInsert Then
accessDatabase.InsertIntoTable("MyTable", ColNames, Values)
End If
This part of the code handles gathering data to insert into my access database.
Public Sub InsertIntoTable(ByRef TableName As String, ByRef ColumnName() As String, ByRef KeyValue() As Object)
'ColumnName and KeyValue need to have the same number of elements
'be careful when attemping to insert a value into the PrimaryKey Column as it may be of a type that cannot but manually changed
'INSERT NEW DATA INTO A TABLE
' INSERT INTO {tablename} ([{columnname1}], [{columnname2}], [{columnname3}], ...) VALUES ('{string}', {number}, {boolean}, ...), oledbconnection
Dim ColumnString As String = vbNullString
Dim KeyString As String = vbNullString
For i As Integer = 0 To ColumnName.GetUpperBound(0)
'build the column names part of the string
If i <> ColumnName.GetUpperBound(0) Then
ColumnString = ColumnString & "[" & ColumnName(i) & "], "
Else
ColumnString = ColumnString & "[" & ColumnName(i) & "]"
End If
'build the values part of the string
Dim TempValue As String = vbNullString
If KeyValue(i) <> Nothing Then
If KeyValue(i).GetType.ToString = "System.String" Then
TempValue = "'" & KeyValue(i) & "'"
Else
TempValue = KeyValue(i)
End If
If i <> KeyValue.GetUpperBound(0) Then
KeyString = KeyString & vbNullString & TempValue & ", "
Else
KeyString &= TempValue
End If
Else
Debug.Print("Nothing")
If i <> KeyValue.GetUpperBound(0) Then
KeyString &= ", "
End If
End If
Next
Dim con As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim sql As New OleDbCommand
con.ConnectionString = Connection()
con.Open()
Dim commandText As String = "INSERT INTO " & TableName & " (" & ColumnString & ") VALUES (" & KeyString & ")"
Try
sql.Connection = con
sql.CommandText = commandText
da.InsertCommand = sql
da.InsertCommand.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
con.Close()
End Sub
This is the InsertIntoTable function.
The function runs properly and inserts data into my table correctly, but in my debug output I keep noticing this error on every call to da.InsertCommand.ExecuteNonQuery():
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
I was able to use the Visual Studio debugger to narrow it down to ExecuteNonQuery() being where it occurs, but I'm having trouble understanding what it means, and how to go about resolving it. I've attempted changing my intVars to Strings with no luck to resolving the exception, and I'm also extremely curious why this isn't being caught by my Try...Catch.

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.

import from excel error in datagridview vb.net 2010

i am importing excel file in datagridview below is my code
'ofdImport.Filter = "Excel Files (*.xls)|*.xls"
ofdImport.FileName = ""
If ofdImport.ShowDialog(Me) = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
txtPath.Text = ofdImport.FileName
If txtPath.Text <> "" Then
chkItemList.Visible = True
dgvImportData.Visible = True
pnlDataMsg.Visible = False
dgvImportData.Columns.Clear()
chkItemList.Items.Clear()
Try
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & txtPath.Text & " '; Extended Properties=Excel 8.0;")
Dim excelSelect As New OleDbCommand
Dim excelAdp As New OleDbDataAdapter
Dim excelSchemaDt As DataTable
Dim dset As New DataSet
If conExcel.State Then conExcel.Close()
conExcel.Open()
excelSelect.Connection = conExcel
excelSchemaDt = conExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim sheetName As String = excelSchemaDt.Rows(0)("TABLE_NAME").ToString()
excelSelect.CommandText = "select * from [" & sheetName & "] "
excelAdp.SelectCommand = excelSelect
excelAdp.TableMappings.Add("Table", "TestTable")
excelAdp.Fill(dset)
dgvImportData.DataSource = dset.Tables(0)
Dim i As Integer
Dim q(dgvImportData.Columns.Count()) As String
For i = 0 To (dgvImportData.Columns.Count - 1)
q(i) = (dgvImportData.Columns(i).HeaderText.ToString())
Next i
conExcel.Close()
i = 0
Dim a As String = ""
'Dim q(frmImportWizard.gridImport.Columns.Count()) As String
For i = 0 To dgvImportData.Columns.Count - 1
a = dgvImportData.Columns(i).HeaderText.ToString()
'CheckedListBox1.Items.Add(a)
chkItemList.Items.Add(a)
Next i
chkAll.Visible = True
chkAll.Checked = False
lblColumnData.Visible = True
Catch ex As Exception
'MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End If
excel file contains phone nos for eg "9874532146/8456663225" in one colms and also i have "98455566966" in same colmns
the problem here is my code is not reading the phone numbers
without "/" its going blank in grid
please help
replaced connection string
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & txtPath.Text & "';Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""")

vb.net xls to csv with quotes?

I have a xls file, or a csv without quotes, and using vb.net need to turn it into a csv with quotes around every cell. If I open the xls/csv without quotes in MS Access, set every column to text and then export it, its in the format I need. Is there an easier way? If not, how do I do replicate this in vb.net? Thanks.
If you use the .Net OLE DB provider, you can specify the .csv formatting details in a schema.ini file in the folder your data files live in. For the 'unquoted' .csv the specs
should look like
[noquotes.csv] <-- file name
ColNameHeader=True <-- or False
CharacterSet=1252 <-- your encoding
Format=Delimited(,) <--
TextDelimiter= <-- important: no " in source file
Col1=VendorID Integer <-- your columns, of course
Col2=AccountNumber Char Width 15
for the 'quoted' .csv, just change the name and delete the TextDelimiter= line (put quotes around text fields is the default).
Then connect to the Text Database and execute the statement
SELECT * INTO [quotes.csv] FROM [noquotes.csv]
(as this creates quotes.csv, you may want to delete the file before each experimental run)
Added to deal with "Empty fields must be quoted"
This is a VBScript demo, but as the important things are the parameters for .GetString(), you'll can port it to VB easily:
Dim sDir : sDir = resolvePath( "§LibDir§testdata\txt" )
Dim sSrc : sSrc = "noquotes.csv"
Dim sSQL : sSQL = "SELECT * FROM [" & sSrc & "]"
Dim oTxtDb : Set oTxtDb = New cADBC.openDb( Array( "jettxt", sDir ) )
WScript.Echo goFS.OpenTextFile( goFS.BuildPath( sDir, sSrc ) ).ReadAll()
Dim sAll : sAll = oTxtDb.GetSelectFRO( sSQL ).GetString( _
adClipString, , """,""", """" & vbCrlf & """", "" _
)
WScript.Echo """" & Left( sAll, Len( sAll ) - 1 )
and output:
VendorID;AccountNumber;SomethingElse
1;ABC 123 QQQ;1,2
2;IJK 654 ZZZ;2,3
3;;3,4
"1","ABC 123 QQQ","1,2"
"2","IJK 654 ZZZ","2,3"
"3","","3,4"
(german locale, therefore field separator ; and decimal symbol ,)
Same output from this VB.Net code:
Imports ADODB
...
Sub useGetString()
Console.WriteLine("useGetString")
Const adClipString As Integer = 2
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim sAll As String
cn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=M:\lib\kurs0705\testdata\txt\;" _
& "Extended Properties=""text;"""
cn.Open()
rs = cn.Execute("SELECT * FROM [noquotes.csv]")
sAll = rs.GetString( adClipString, , """,""", """" & vbCrLf & """", "" )
cn.Close()
sAll = """" & Left( sAll, Len( sAll ) - 1 )
Console.WriteLine( sAll )
End Sub
Check out the method at this link.
What you can do to make sure quotes go around is append quotes to the beginning and end of each column data in the loop that is putting the column data in the file.
for example make the loop like this:
For InnerCount = 0 To ColumnCount - 1
Str &= """" & DS.Tables(0).Rows(OuterCount).Item(InnerCount) & ""","
Next
Public Class clsTest
Public Sub Test
Dim s as string = "C:\!Data\Test1.csv"
Dim Contents As String = System.IO.File.ReadAllText(s)
Dim aryLines As String() = Contents.Split(New String() { Environment.Newline }, StringSplitOptions.None)
Dim aryParts() As String
Dim aryHeader() As String
Dim dt As System.Data.DataTable
For i As Integer = 0 To aryLines.Length - 1
aryParts = SplitCSVLine(aryLines(i))
If dt Is Nothing And aryHeader Is Nothing Then
aryHeader = CType(aryParts.Clone, String())
ElseIf dt Is Nothing And aryHeader IsNot Nothing Then
dt = DTFromStringArray(aryParts, 1000, "", aryHeader)
Else
DTAddStringArray(dt, aryParts)
End If
Next
dt.dump
End Sub
Public Shared Function SplitCSVLine(strCSVQuotedLine As String) As String()
Dim aryLines As String() = strCSVQuotedLine.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
Dim aryParts As String() = Nothing
For i As Integer = 0 To aryLines.Length - 1
Dim regx As New Text.RegularExpressions.Regex(",(?=(?:[^\""]*\""[^\""]*\"")*(?![^\""]*\""))")
aryParts = regx.Split(aryLines(i))
For p As Integer = 0 To aryParts.Length - 1
aryParts(p) = aryParts(p).Trim(" "c, """"c)
Next
Next
Return aryParts
End Function
Public Shared Function DTFromStringArray(ByVal aryValues() As String, Optional ByVal intDefaultColumnWidth As Integer = 255, Optional ByVal strTableName As String = "tblArray", Optional ByVal aryColumnNames() As String = Nothing) As DataTable
If String.IsNullOrWhiteSpace(strTableName) Then strTableName = "tblArray"
Dim dt As DataTable = New DataTable(strTableName)
Dim colNew(aryValues.GetUpperBound(0)) As DataColumn
If aryColumnNames Is Nothing Then
ReDim aryColumnNames(aryValues.Length)
Else
If aryColumnNames.GetUpperBound(0) < aryValues.GetUpperBound(0) Then
ReDim Preserve aryColumnNames(aryValues.Length)
End If
End If
For x As Integer = aryColumnNames.GetLowerBound(0) To aryColumnNames.GetUpperBound(0)
If String.IsNullOrWhiteSpace(aryColumnNames(x)) Then
aryColumnNames(x) = "Field" & x.ToString
Else
aryColumnNames(x) = aryColumnNames(x)
End If
Next
For i As Integer = 0 To aryValues.GetUpperBound(0)
colNew(i) = New DataColumn
With colNew(i)
.ColumnName = aryColumnNames(i) '"Value " & i
.DataType = GetType(String)
.AllowDBNull = False
.DefaultValue = ""
.MaxLength = intDefaultColumnWidth
.Unique = False
End With
Next
dt.Columns.AddRange(colNew)
Dim pRow As DataRow = dt.NewRow
For i As Integer = aryValues.GetLowerBound(0) To aryValues.GetUpperBound(0)
pRow.Item(i) = aryValues(i)
Next
dt.Rows.Add(pRow)
Return dt
End Function
Public Shared Sub DTAddStringArray(ByRef dt As DataTable, ByVal aryRowValues() As String)
Dim pRow As DataRow
pRow = dt.NewRow
For i As Integer = aryRowValues.GetLowerBound(0) To aryRowValues.GetUpperBound(0)
pRow.Item(i) = aryRowValues(i)
Next
dt.Rows.Add(pRow)
End Sub
End Class