This is my code :
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim JsonSub As String = "{""subdomain01"":[""21"",""subdomain01"",""4""],""subdomain02"":[""22"",""subdomain02"",""4""]}"
Dim objSub As JObject = JObject.Parse(JsonSub)
Dim dataSub As List(Of JToken) = objSub.Children().ToList
For Each subdomain As JProperty In dataSub
subdomain.CreateReader()
For Each pSub As JObject In subdomain.Value.ToString
MsgBox(pSub.ToString)
Next
Next
End Sub
How can I get value in array of that string :
[""21"",""subdomain01"",""4""]
If you want to get just that, do a split:
Dim resultarray As String() = JsonSub.Split(":")(1).Split(",")
Dim result As String = resultarray(0) & "," & resultarray(1) & "," & resultarray(2)
as JsonSub.Split(CChar(":"))(1) will return [""21"",""subdomain01"",""4""],""subdomain02""
and in turn, split that with the comma will net you 4 substring between those ",". You only need to take the first 3, and the result is as shown.
Related
I get this SQL Server error and I can't figure out where the trouble is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
xception Details: System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.'
Source Error: Line: 46
Error Line: cmdsql.ExecuteNonQuery()
Code:
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
On Error Resume Next
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
FileAdd.Text = OpenFileDialog1.FileName
connexcel = New OleDbConnection("provider = Microsoft.ace.OLEDB.12.0; data source =" & FileAdd.Text & "; Extended Properties = Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
ExcelSheetList.Items.Add(sheet)
Next
End Sub
Private Sub ExcelSheetList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelSheetList.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & ExcelSheetList.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
DGVImpData.DataSource = dsexcel.Tables(0)
DGVImpData.ReadOnly = True
End Sub
Sub connections()
connsql = New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
connsql.Open()
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
For line As Integer = 0 To DGVImpData.RowCount - 2
Call connections()
Dim save As String = "insert into InvoiceData values ('" & DGVImpData.Rows(line).Cells(0).Value & "', '" & DGVImpData.Rows(line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
Keep your database objects local so you can be sure they are closed and disposed. Enclosing these objects with `Using...End Using blocks will accomplish this even if there is an error. You don't need variables for DataAdapters, DataSets, or DataReaders. I suggest only one form level variable for the Excel connection string since it is used in 2 methods.
A little bit of Linq will get the retrieved sheet names from the DataTable and fill an array. The array can then be passed to the list box with .AddRange.
I wouldn't use the SelectedIndexChanged event because the user can too easily click the wrong sheet or change their mind. I used a Button.Click event to fill the grid.
The Sql connection string looks strange to me. I suggest you test it separately. If it doesn't work, this is a good resource. https://www.connectionstrings.com/
I would specifically state the column names in the Insert statement. Replace FirstColumnName and SecondColumnName with the real column names. The parameter names can be anything you wish as long as the names in the statement match the names in the Parameters.Add method. I have guessed at the datatypes and the size. Check your database for correct values.
We add the parameters only once outside the loop then change only values inside the loop.
Private ExcelConString As String
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
Dim strFileName As String
Dim dtSheets As DataTable
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
strFileName = OpenFileDialog1.FileName
ExcelConString = "provider = Microsoft.ace.OLEDB.12.0; data source =" & strFileName & "; Extended Properties = Excel 8.0;"
Using connexcel = New OleDbConnection(ExcelConString)
connexcel.Open()
dtSheets = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
Dim exSheets() As Object = (From dRow In dtSheets.AsEnumerable() Select dRow("TABLE_Name")).ToArray
ExcelSheetList.Items.AddRange(exSheets)
End Sub
Private Sub DisplayData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayData.Click
Dim dt As New DataTable
Using cn As New OleDbConnection(ExcelConString)
'In older versions of Visual Studio you may have to use String.Format instead of the interpolated string.
Using cmd As New OleDbCommand($"select * from [{ExcelSheetList.Text}];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DGVImpData.DataSource = dt
DGVImpData.ReadOnly = True
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
Using cn As New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
Using cmd As New SqlCommand("Insert Into InvoiceData (FirstColumnName, SecondColumnName) Values (#FirstColumn, #SecondColumn);", cn)
cmd.Parameters.Add("#FirstColumn", SqlDbType.VarChar, 100)
cmd.Parameters.Add("#SecondColumn", SqlDbType.VarChar, 100)
cn.Open()
For line As Integer = 0 To DGVImpData.RowCount - 2
cmd.Parameters("#FirstColumn").Value = DGVImpData.Rows(line).Cells(0).Value
cmd.Parameters("#SecondColumn").Value = DGVImpData.Rows(line).Cells(1).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
As to error handling... On Error Resume Next is generally not used in new code. We have Try...Catch...Finally blocks. After your code is running add these blocks where needed.
EDIT
To use String.Format...
Using cmd As New OleDbCommand(String.Format("select * from [{0}];", ExcelSheetList.Text))
The first parameter is the string in which you wish to place variables. It contains indexed placeholders enclosed in braces. The following parameters are the variables you want for the placeholder substitution.
Thank you for helping me to a fixed error in my code. Here is Final code without System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.' error.
Now I tried to improve code with the last section(mention below) to define parameters for exporting data. Because I have a large number of data for exporting to SQL Server I get a Timeout error. Can anyone be able to improve code for quick exporting data to SQL Server?
connsql.Open() "System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'"
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub Import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub PKGAbtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpExcelFile.Click
On Error Resume Next
'OpenFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx|All files (*.*)|*.*"
PKGAofdImpOpenExcel.ShowDialog()
PKGAtxtImpFileAdd.Text = PKGAofdImpOpenExcel.FileName
connexcel = New OleDbConnection("provider=Microsoft.ace.OLEDB.12.0;data source=" & PKGAtxtImpFileAdd.Text & ";Extended Properties=Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
PKGAtxtImpExlSheetL.Items.Add(sheet)
Next
End Sub
Private Sub PKGAtxtImpExlSheetL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAtxtImpExlSheetL.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & PKGAtxtImpExlSheetL.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
PKGAdgvImpData.DataSource = dsexcel.Tables(0)
PKGAdgvImpData.ReadOnly = True
End Sub
'Last Section
Sub Connectonsql()
connsql = New SqlConnection("Data Source=DESKTOP-MIQGJTK\MSSMLBIZ;Initial Catalog=PkGlobalAccounting;Integrated Security=True")
connsql.Open()
End Sub
Private Sub PKGAbtnImpSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpSave.Click
For Line As Integer = 0 To PKGAdgvImpData.RowCount - 2
Call Connectonsql()
Dim save As String = "insert into Test values('" & PKGAdgvImpData.Rows(Line).Cells(0).Value & "','" & PKGAdgvImpData.Rows(Line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("Data Saved Successfully")
PKGAdgvImpData.Columns.Clear()
End Sub
Thanks for Your Help.
Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)
Here is my code:
Private Sub tvw1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvw1.AfterSelect
Dim MPath As String
MPath = "D:\VB6_Projects\ChurchPresentation\ChurchPresentation\Bible_TH\Bible1971\"
Dim str As String
Dim strArr() As String
Dim count As Integer
If tvw1.Nodes(0).Nodes(0).Nodes(0).IsSelected = True Then
rtbThai.LoadFile(MPath & "genesis1.txt", RichTextBoxStreamType.PlainText)
str = rtbThai.Text
strArr = str.Split(ChrW(10))
For count = 0 To strArr.Length - 1
lstThai1971.Controls.Add(strArr(count))
'MessageBox.Show(strArr(count))
Next
End If
End Sub
It works if I show the messagebox, buf it doesn’t if I use lstThai1971.Controls.add(strArr(count)).
What is wrong in this code?
Assuming lstThai1971 is a ListBox of sorts, I expect you want to :
lstThai1971.Items.Add(strArr(count))
You could also add the entire array using AddRange
lstThai1971.Items.AddRange(strArr)
I wrote the following code:
Public Class Form1
Private Structure udtThing
Dim SomeText As String
Dim SomeElements() As String
Public Shared Function CreateInstance() As udtThing
Dim result As New udtThing
result.SomeText = String.Empty
ReDim result.SomeElements(2)
result.SomeElements(0) = String.Empty
result.SomeElements(1) = String.Empty
result.SomeElements(2) = String.Empty
Return result
End Function
End Structure
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings() As udtThing
nThings = Array.CreateInstance(GetType(udtThing), 10)
End Sub
End Class
I partly works, nThings becomes an array of 11 udtThings.
But .SomeElements is not redimmed to 3 strings of String.Empty, but it is "Nothing" instead.
Does anybody see where I went wrong?
Thank you very much!
By design, a Redim is required. Array.CreateInstance() isn't going to perform that operation, it can't guess what size is required. You'll have to help:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings(10) As udtThing
For ix As Integer = 0 To UBound(nThings)
nThings(ix) = udtThing.CreateInstance()
Next
End Sub
I have a filepath that I would like to pull the starting directory job number from the beginning of the filepath. Except I don't know how to just pull the number string out of the filepath string. (i.e.: filepath= Q:\2456_blah_blah\file.txt - or something) I'd like to just pull '2456' as a string,
then put that number string into TextBox2 I've created on my form.
The code I have so far spits out a '0' instead of the number string desired.
Any help would be much appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.OpenFileDialog1.FileName = Nothing
If Me.OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = Me.OpenFileDialog1.FileName
End If
If GetInfo() = True Then
For Each Xitem In ExcelRowList
Dim lvitem As ListViewItem
lvitem = Me.ListView1.Items.Add(Xitem.C1)
Next
End If
'''Here is where I call the GetFilePathOnly function
TextBox2.Text = GetFilePathOnly(TextBox1.Text)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
'''Section below is what defines my number string, then I call it above for the Button1.Click operation(towards the end)
Private Function GetFilePathOnly(ByVal Fullpath As String) As String
Dim File As String = Fullpath
Dim number As Double = Val(File)
Dim outcome As String = number.ToString 'File.Substring(0, File.LastIndexOf("\") + 1)
Return outcome
End Function
Thanks
You could also use a regular expression easily.
Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("Q:\2456_blah_blah\file.txt").Value
A lazy way would be to use Split:
TextBox2.Text = path.Split("\")(1).Split("_")(0)