Related
Updated code. I think its close but the dgv doesn't load with any data.
Public Class CloseJob
Public sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Public con As New SqlConnection(sqlcon)
Public job As String
Public Async Function GetDataAsync(ByVal sql As String, ByVal sqlcon As String) As Task(Of DataTable)
Dim dt As New DataTable
Dim cmd As New SqlCommand(sql, con)
Using da = New SqlDataAdapter(sql, sqlcon)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("#Job2", job)
Await Task.Run(Function()
da.Fill(dt)
End Function)
End Using
Return dt
End Function
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Visible
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Try
job = txtJob.Text
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As String
sql = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
con.Open()
Dim data = Await GetDataAsync(sql, sqlcon)
dgvJob.DataContext = data
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
Catch ex As Exception
End Try
Refresh.Visibility = Windows.Visibility.Hidden
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Hidden
txtJob.Focus()
End Sub
End Class
I recommend you clean your code up a bit and make methods that only do one thing - don't have a ReadDatabase that also fiddles with controls etc
DataAdapter can take a sql string and a connection string, it knows how to make a connection and open it etc. It tidies things up to hand all that off to the DA
And maybe put that massive SQL string into a Resources file
Private Async Function GetComponentsDataTable() as Task(Of DataTable)
Dim con As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql as String = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
Using da as New SqlDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#Job2", job) 'see https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/'
Dim dt As New DataTable
Await Task.Run(Sub() da.Fill(dt)) 'also, see note from AlexB
Return dt
End Using
End Sub
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Dim dt = Await GetComponentsDataTable()
dgvJob.AutoGenerateColumns = True
dgvJob.DataContext = dt.DefaultView
dgvJob.CanUserAddRows = False
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
This is your code modified on the fly, start from here as I don’t know if works well or if there needs changes without your database and other parameters.
Public con As New SqlConnection
Public job As String
Private Sub ReadDatabase()
Dim bgThread As Threading.Thread = New Threading.Thread(Sub()
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As New SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Using con = New SqlConnection(sqlcon)
con.Open()
sql = New SqlCommand("SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " &
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " &
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " &
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " &
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " &
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " &
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " &
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " &
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " &
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " &
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2", con)
sql.Parameters.AddWithValue("#Job2", job)
da.SelectCommand = sql
Dim dt As New DataTable
da.Fill(dt)
Invoke(Sub()
dgvJob.DataContext = dt.DefaultView
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
End Sub)
End Using
End Sub) With {
.IsBackground = True
}
bgThread.Start()
End Sub
Public Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
job = txtJob.Text
ReadDatabase()
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
I have a winforms app that connects to a SQL Server database. On the form to add a new golfer to the golfers table, there are combo boxes for t-shirt size and gender. When a new record is submitted, all the inputs are supposed to clear so that the form is blank when it is re-initialized to add the next record.
The problem is that, when the form is re-initialized, the previously added golfer's gender and t-shirt size are still in their respective combo boxes, while every other input is blank. I've gone through the code, and there's nothing in the load event for the form that would do this. How can I fix this?
Here is my code:
'Button on main form to open the input form to add new golfer
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
'Show Form To Add New Golfer
frmAddGolfer.ShowDialog()
'Refresh Form
frmManageGolfers_Load(sender, e)
End Sub
_______________________________________________________________
Private Sub frmAddGolfer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Clear any previous data
ClearForm()
End Sub
______________________________________________________________
'load event for input form
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
Dim strSelectPlayerID As String = ""
Dim dtDataTable As DataTable = New DataTable
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strStreetAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strPhoneNumber As String = ""
Dim strEmail As String = ""
Dim intGenderID As Integer
Dim intShirtSizeID As Integer
Dim intRowsAffected As Integer
Dim intNextHighestRecordID As Integer
'Reset control colors
txtFirstName.BackColor = Color.White
txtLastName.BackColor = Color.White
txtAddress.BackColor = Color.White
txtCity.BackColor = Color.White
txtState.BackColor = Color.White
txtZip.BackColor = Color.White
txtPhoneNumber.BackColor = Color.White
txtEmailAddress.BackColor = Color.White
cboGender.BackColor = Color.White
cboShirtSizes.BackColor = Color.White
' this will hold our EXECUTE statement
Dim cmdAddPlayer As OleDb.OleDbCommand
' check to make sure all fields have data. No data no update!
If Validation(txtFirstName.Text, txtLastName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text, txtPhoneNumber.Text, txtEmailAddress.Text, CStr(cboGender.SelectedItem), CStr(cboShirtSizes.SelectedItem)) = True Then
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
' and close the form/application
Me.Close()
End If
Try
' make the connection
cmdAddPlayer = New OleDb.OleDbCommand()
'Set Values For stored procedure parameters
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strStreetAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strPhoneNumber = txtPhoneNumber.Text
strEmail = txtEmailAddress.Text
intGenderID = CInt(cboGender.SelectedIndex) + 1
intShirtSizeID = CInt(cboShirtSizes.SelectedIndex) + 1
' Build the select statement using PK from name selected
' Text to build call to stored proc
cmdAddPlayer.CommandType = CommandType.StoredProcedure
cmdAddPlayer.CommandText = "EXECUTE uspAddGolfer '" &
intNextHighestRecordID & "', " &
"'" & strFirstName & "', " &
"'" & strLastName & "', " &
"'" & strStreetAddress & "', " &
"'" & strCity & "', " &
"'" & strState & "', " &
"'" & strZip & "', " &
"'" & strPhoneNumber & "', " &
"'" & txtEmailAddress.Text & "', " &
"'" & intGenderID & "', " &
"'" & intShirtSizeID & "'"
'EXECUTE stored proc
cmdAddPlayer = New OleDb.OleDbCommand(cmdAddPlayer.CommandText, m_conAdministrator)
' Update the row with execute the statement
intRowsAffected = cmdAddPlayer.ExecuteNonQuery()
' have to let the user know what happened
If intRowsAffected = 1 Then
MessageBox.Show("New record added successfully")
'clear inputs and close form
ClearForm()
Me.Close()
Else
MessageBox.Show("Update failed")
'clear inputs and close form
ClearForm()
Me.Close()
End If
' close the database connection
CloseDatabaseConnection()
Catch Ex As Exception
'Display Error Message To User
MessageBox.Show(Ex.Message)
End Try
End If
End Sub
______________________________________________________________
Private Sub ClearForm()
'Clear form and reset control colors
txtFirstName.Clear()
txtLastName.Clear()
txtAddress.Clear()
txtCity.Clear()
txtState.Clear()
txtZip.Clear()
txtPhoneNumber.Clear()
txtEmailAddress.Clear()
cboGender.ResetText()
cboShirtSizes.ResetText()
txtFirstName.BackColor = Color.White
txtLastName.BackColor = Color.White
txtAddress.BackColor = Color.White
txtCity.BackColor = Color.White
txtState.BackColor = Color.White
txtZip.BackColor = Color.White
txtPhoneNumber.BackColor = Color.White
txtEmailAddress.BackColor = Color.White
cboGender.BackColor = Color.White
cboShirtSizes.BackColor = Color.White
End Sub
The fact that you're calling an event handler directly is a good indication that you're doing it wrong. Don't use default instances at all. Just do it properly and create a new instance each time. That way, the load event handler will be executed naturally as a result of the form being loaded. Create the form with a Using statement so it is disposed when you're done with it.
Using dialogue As New frmAddGolfer
dialogue.ShowDialog()
End Using
If you do it this way, there will be no need to clear the form anyway, because it will be a new form.
The following code seems to do the trick.
Private Sub frmAddGolfer_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
ComboBox1.SelectedIndex = -1
ComboBox2.SelectedIndex = -1
End Sub
I am not familiar with ResetText.
Now, to your data access code. Keep your data objects local so you can control that they are closed and disposed. This is especially important for connections which are precious resources. Using...End Using blocks will do this for you even if there is an error.
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
Dim intRowsAffected As Integer
' check to make sure all fields have data. No data no update!
If Not Validation(txtFirstName.Text, txtLastName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text, txtPhoneNumber.Text, txtEmailAddress.Text, CStr(cboGender.SelectedItem), CStr(cboShirtSizes.SelectedItem)) Then
MessageBox.Show("All data must be filled in.")
Return
End If
Using cn As New SqlConnection("Your connection string")
Using cmdAddPlayer As New SqlCommand("uspAddGolfer", cn)
cmdAddPlayer.CommandType = CommandType.StoredProcedure
cmdAddPlayer.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
cmdAddPlayer.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text
cmdAddPlayer.Parameters.Add("#Address", SqlDbType.VarChar).Value = txtAddress.Text
cmdAddPlayer.Parameters.Add("#City", SqlDbType.VarChar).Value = txtCity.Text
cmdAddPlayer.Parameters.Add("#State", SqlDbType.VarChar).Value = txtState.Text
cmdAddPlayer.Parameters.Add("#Zip", SqlDbType.VarChar).Value = txtZip.Text
cmdAddPlayer.Parameters.Add("#Phone", SqlDbType.VarChar).Value = txtPhoneNumber.Text
cmdAddPlayer.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtEmailAddress.Text
cmdAddPlayer.Parameters.Add("#Gender", SqlDbType.Int).Value = cboGender.SelectedIndex + 1 'Index is an Integer
cmdAddPlayer.Parameters.Add("#ShirtSize", SqlDbType.Int).Value = cboShirtSizes.SelectedIndex + 1
cn.Open()
intRowsAffected = cmdAddPlayer.ExecuteNonQuery()
End Using
End Using
If intRowsAffected = 1 Then
MessageBox.Show("New record added successfully")
Close()
Else
MessageBox.Show("Update failed")
Close()
End If
End Sub
You will have to check your stored procedure to get the correct parameter names and data types.
I'm trying to import a text file into an SQL server. I need to read data inside the file when I upload it and send all the data to an SQL server. Of course inside the SQL I have primary keys where it's going to increment when a new line of data is finished.
HELP!
With Cinchoo ETL - an open source ETL framework, you can load the entire file to database with few lines of code as below (the code is in c#, hope you can translate it to vb.net)
string connectionstring =
#"Data Source=(localdb)\v11.0;Initial Catalog=TestDb;Integrated Security=True";
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionstring))
{
using (var dr = new ChoCSVReader<Customer>
("Cust.csv").WithFirstLineHeader().AsDataReader())
{
bcp.DestinationTableName = "dbo.Customers";
bcp.EnableStreaming = true;
bcp.BatchSize = 10000;
bcp.BulkCopyTimeout = 0;
bcp.NotifyAfter = 10;
bcp.SqlRowsCopied += delegate (object sender, SqlRowsCopiedEventArgs e)
{
Console.WriteLine(e.RowsCopied.ToString("#,##0") + " rows copied.");
};
bcp.WriteToServer(dr);
}
}
For more details, visit the codeproject article
Disclosure: I'm the author of this library.
This is an interesting question. I did this a looonnngggg time ago. See the code below, for a solution to your question.
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Also, see ALL the code below, for several similar, and related, tasks. Notice, I added a few comments, but not too many...
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Imports System.Configuration
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
"initial catalog=NORTHWIND;Trusted_Connection=True"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM [Order Details]"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub
Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object,
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles DataGridView1.CellFormatting
If e.ColumnIndex = DataGridView1.Columns(3).Index _
AndAlso e.Value IsNot Nothing Then
'
If CInt(e.Value) < 10 Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.ForeColor = Color.LightGoldenrodYellow
End If
'
End If
'
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim SQLConnectionString As String = "Data Source=Excel-PC\SQLEXPRESS;" & _
"Initial Catalog=Northwind;" & _
"Trusted_Connection=True"
' Open a connection to the AdventureWorks database.
Using SourceConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
SourceConnection.Open()
' Perform an initial count on the destination table.
Dim CommandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.Orders;", _
SourceConnection)
Dim CountStart As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", CountStart)
' Get data from the source table as a AccessDataReader.
'Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
' "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
' "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & "C:\Users\Excel\Desktop\" & ";" & _
"Extended Properties=""Text;HDR=No"""
Dim TextConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim TextCommand As New OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection)
TextConnection.Open()
Dim TextDataReader As OleDbDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess)
' Open the destination connection.
Using DestinationConnection As SqlConnection = _
New SqlConnection(SQLConnectionString)
DestinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using BulkCopy As SqlBulkCopy = _
New SqlBulkCopy(DestinationConnection)
BulkCopy.DestinationTableName = _
"dbo.Orders"
Try
' Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the AccessDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
TextDataReader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim CountEnd As Long = _
System.Convert.ToInt32(CommandRowCount.ExecuteScalar())
'Console.WriteLine("Ending row count = {0}", CountEnd)
'Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
End Using
End Using
'Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
'Dim TextLine As String
'If System.IO.File.Exists(FILE_NAME) = True Then
' Dim objReader As New System.IO.StreamReader(FILE_NAME)
' Do While objReader.Peek() <> -1
' TextLine = TextLine & objReader.ReadLine() & vbNewLine
' Loop
'Else
' MsgBox("File Does Not Exist")
'End If
'Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
'Dim cmd As New SqlCommand
'cmd.Connection = cn
'cmd.Connection.Close()
'cmd.Connection.Open()
'cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
'cmd.ExecuteNonQuery()
'cmd.Connection.Close()
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
' Define the Column Definition
Dim dt As New DataTable()
dt.Columns.Add("OrderID", GetType(Integer))
dt.Columns.Add("CustomerID", GetType(String))
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("OrderDate", GetType(Date))
dt.Columns.Add("RequiredDate", GetType(Date))
dt.Columns.Add("ShippedDate", GetType(Date))
dt.Columns.Add("ShipVia", GetType(Integer))
dt.Columns.Add("Freight", GetType(Decimal))
dt.Columns.Add("ShipName", GetType(String))
dt.Columns.Add("ShipAddress", GetType(String))
dt.Columns.Add("ShipCity", GetType(String))
dt.Columns.Add("ShipRegion", GetType(String))
dt.Columns.Add("ShipPostalCode", GetType(String))
dt.Columns.Add("ShipCountry", GetType(String))
Using cn = New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
cn.Open()
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\Users\Excel\Desktop\OrdersTest.csv")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = dt.NewRow()
For currColumn = 0 To dt.Columns.Count - 1
sqlColumnDataType = dt.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
dt.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
'Return False
Finally
dr = Nothing
End Try
End While
Using copy As New SqlBulkCopy(cn)
copy.DestinationTableName = "[dbo].[Orders]"
copy.WriteToServer(dt)
End Using
End Using
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
'Dim cnn As SqlConnection
'Dim connectionString As String
'Dim sql As String
'connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
'"initial catalog=NORTHWIND;Trusted_Connection=True"
'cnn = New SqlConnection(connectionString)
'cnn.Open()
'GetCsvData("C:\Users\Excel\Desktop\OrdersTest.csv", dbo.Orders)
End Sub
Public Shared Function GetCsvData(ByVal CSVFileName As String, ByRef CSVTable As DataTable) As Boolean
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
Dim currentRow As String()
Dim dr As DataRow
Dim sqlColumnDataType As String
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName)
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
dr = CSVTable.NewRow()
For currColumn = 0 To CSVTable.Columns.Count - 1
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name
Select Case sqlColumnDataType
Case "String"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn))
End If
Case "Decimal"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = 0
Else
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn))
End If
Case "DateTime"
If String.IsNullOrEmpty(currentRow(currColumn)) Then
dr.Item(currColumn) = ""
Else
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn))
End If
End Select
Next
CSVTable.Rows.Add(dr)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid." & vbCrLf & "Terminating Read Operation.")
reader.Close()
reader.Dispose()
Return False
Finally
dr = Nothing
End Try
End While
reader.Close()
reader.Dispose()
Return True
End Function
Private Sub DataGridView1_RowValidating(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
End Sub
End Class
One more to try . . .
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file As String = "Import.txt"
Dim path As String = "C:\Users\path_to_text_file\"
Dim ds As New DataSet
Try
If IO.File.Exists(IO.Path.Combine(path, file)) Then
Dim ConStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
path & ";Extended Properties=""Text;HDR=No;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
file, conn)
da.Fill(ds, "TextFile")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
i am trying to insert my listview items into my MS access database.
here is the code:
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewSMS.Click
cn.ConnectionString = newConn
If cn.State = ConnectionState.Closed Then
cn.Open()
For x = 0 To ListView2.Items.Count - 1
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & ListView2.Items(x).SubItems(0).Text & "', '" & ListView1.Items(x).SubItems(1).Text & "','" & ListView1.Items(x).SubItems(2).Text & "','" & ListView1.Items(x).SubItems(3).Text & ")"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
'End With
Next
End If
cn.Close()
End Sub
my error is:
Value of '0' is not valid for 'index'
my problem is in inserting the values. Please Help me... thanks everyone - Chris
'Try this..
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(sender As Object, e As EventArgs) Handles btnNewSMS.Click
For Each x As ListViewItem In ListView2.Items
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & _
x.SubItems(0).Text & "', '" & _
x.SubItems(1).Text & "','" & _
x.SubItems(2).Text & "','" & _
x.SubItems(3).Text & "')"
'Add also the last single qoute before the parenthesis ^_^
'to make sure the query works..
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
End With
Next
End Sub
Use this code for more than one form’s
DataTransfer.vb
Public Class DataTransfer
Public Sub ListToData(ByVal strcon As String, ByVal strcmd As String, ByVal listview As ListView)
Dim i As Integer = 0
Dim k As Integer = 0
Dim item As New ListViewItem
Dim con As New System.Data.OleDb.OleDbConnection(strcon)
Dim cmd As New System.Data.OleDb.OleDbCommand(strcmd, con)
Try
MessageBox.Show(listview.Items.Count)
While i < listview.Items.Count
item = New ListViewItem()
item = listview.Items(i).Clone
itemToString(item, strcmd)
con.Open()
cmd.CommandText = strcmd
cmd.ExecuteNonQuery()
MessageBox.Show("saved")
i += 1
End While
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
MessageBox.Show(strcmd)
End Sub
Private Sub itemToString(ByVal item As ListViewItem, ByRef strcmd As String)
Dim k As Integer = 1
strcmd += "VALUES ("
strcmd += "'" & item.Text & "'"
MessageBox.Show("subitems" + item.SubItems.Count.ToString)
While k < item.SubItems.Count
strcmd += ",'" & item.SubItems(k).Text & "'"
k += 1
End While
strcmd += ")"
End Sub
End Class
Form1.vb
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim datatransfer As New DataTransfer
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\schoolDB.accdb"
Dim cmd As String = "INSERT INTO Stu_Info (C_ID, ADM_No, S_Name)"
datatransfer.ListToData(con, cmd, ListView1)
End Sub
End Class
I have the following code:
Imports System.Data.SqlClient
Public Class Main
Protected WithEvents DataGridView1 As DataGridView
Dim instForm2 As New Exceptions
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startpayrollButton.Click
Dim ssql As String = "select MAX(payrolldate) AS [payrolldate], " & _
"dateadd(s, 518399, max(payrolldate)) AS [Sunday]" & _
"from dbo.payroll" & _
" where payrollran = 'no'"
Dim oCmd As System.Data.SqlClient.SqlCommand
Dim oDr As System.Data.SqlClient.SqlDataReader
oCmd = New System.Data.SqlClient.SqlCommand
Try
With oCmd
.Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx")
.Connection.Open()
.CommandType = CommandType.Text
.CommandText = ssql
oDr = .ExecuteReader()
End With
If oDr.Read Then
payperiodstartdate = oDr.GetDateTime(1)
payperiodenddate = payperiodstartdate.AddDays(7)
Dim ButtonDialogResult As DialogResult
ButtonDialogResult = MessageBox.Show(" The Next Payroll Start Date is: " & payperiodstartdate.ToString() & System.Environment.NewLine & " Through End Date: " & payperiodenddate.ToString())
If ButtonDialogResult = Windows.Forms.DialogResult.OK Then
exceptionsButton.Enabled = True
startpayrollButton.Enabled = False
End If
End If
oDr.Close()
oCmd.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
oCmd.Connection.Close()
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
Dim connection As System.Data.SqlClient.SqlConnection
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim ds As New DataSet
Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration into Scratchpad3" & _
" FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber" & _
" where [Exceptions].exceptiondate between #payperiodstartdate and #payperiodenddate" & _
" GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," & _
" [Exceptions].code, [Exceptions].exceptiondate"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
adapter.SelectCommand = _CMD
Try
adapter.Fill(ds)
If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
'it's empty
MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
connection.Close()
Exceptions.saveButton.Enabled = False
Exceptions.Hide()
Else
connection.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
connection.Close()
End Try
Exceptions.Show()
End Sub
Private Sub payrollButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollButton.Click
Payrollfinal.Show()
End Sub
End Class
and when I run this code, I get the following error
System.Data.SQLClient.SQLException:
Syntax error converting from datetime
character string, line 57.
Which is this line:
adapter.Fill(ds)
When I debug this, I put the line break on that line and look at the Table Value, which shows 0, but I know that there is data for that time frame. Can anyone please assist?
Check this out -- you may have a problem with nullable datetimes:
Linky