Checking data if exist in Database VB.Net - database

Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDbConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\sjmi.alfie\documents\visual studio 2010\Projects\Sample Ko\WindowsApplication4\MySample.accdb"
If con.State = ConnectionState.Closed Then
con.Open()
MsgBox("connection is open", vbInformation)
Else
MsgBox("connection is close", vbCritical)
End If
End Sub
Private Sub closeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeButton.Click
Me.Close()
End Sub
Private Sub regButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles regButton.Click
Dim strsql As String
Dim numrows As Integer
strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = " & TextBox1.Text & ""
Dim objcmd As New OleDbCommand(strsql, con)
numrows = objcmd.ExecuteScalar() <<<< Error "Data type mismatch in criteria."
If numrows > 0 Then
MsgBox("Record Exists", vbInformation, "Add")
Else
Dim myadapter1 As New OleDbDataAdapter("INSERT INTO [Sample] ([StudNo], [FirsName], [LastName]) VALUES ('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "')", con)
Dim mytable1 As New DataTable
myadapter1.Fill(mytable1)
MsgBox("Success!!")
End If
con.Close()
End Sub
End Class
please help me. Thanks

Try this instead:
strsql = "SELECT COUNT(*) FROM Sample WHERE StudNo = ?"
Dim objcmd As New OleDbCommand(strsql, con)
objcmd.Parameters.AddWithValue("?", TextBox1.Text)
numrows = Convert.ToInt32(objcmd.ExecuteScalar())
It's called a "parameterized query", and it is the preferred way of doing what you intend.

Related

If statement to not allow insert statement to work because a cell is null

I want the code to not allow the complete button to work because the column of "StartTime" is null.
Attached is the code below:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Public Class Etask
Dim con As SqlConnection
Dim cmd As SqlCommand
Private Sub Etask_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub Etask_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Panel1.Left = (Me.Width - Panel1.Width) / 2
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
refreshDGV()
End Sub
Public Sub refreshDGV()
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
'complete button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set FinishTime=#FinishTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully updated!")
refreshDGV()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Me.TasksTableAdapter.FillBy(Me.RestaurantDatabaseDataSet2.Tasks)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.LabelID.Text = DataGridView1.Item(0, i).Value
End Sub
Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set StartTime=#StartTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#StartTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = "Working on it!"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully started!")
refreshDGV()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = Date.Now.ToString("dd MMM yyyy hh:mm:ss")
End Sub
End Class
This is what the application looks like:
I want the code to check for null data in the StartTime column. If its null, then the complete button won't work. Button1 is the button to complete a task.
ExecuteNonQuery returns an integer with the number of rows affected.
If you create the query so that it does not do an update if the column is NULL, then it will return 0, which you can check for.
Also, it is easier to put the connection string in just one place, so that if you need to change it you only have to do so once - it is too easy to miss an occurrence of the string and have to go and edit it again. Often, such data is stored in the settings for the program, but I've made it as a constant for this example:
Public Const CONNSTR As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
'....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "UPDATE Tasks
SET FinishTime = #FinishTime, Status = #Status
WHERE TaskID = #id
AND StartTime IS NOT NULL"
Dim nRowsAffected = 0
Using con As New SqlConnection(CONNSTR),
cmd As New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
con.Open()
nRowsAffected = cmd.ExecuteNonQuery()
End Using
If nRowsAffected = 0 Then
MsgBox("Database not updated - check for empty StartTime.")
Else
MsgBox("Successfully updated!")
End If
refreshDGV()
End Sub
The Using statement makes sure that "unmanaged resources" are released when it is done.

How to import text file in vb.net and insert into SQL server?

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

Insert some data from a listview into a ms access database in vb.net

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

Adding data to Access Database through Visual Basic Form

I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com

Getting Syntax Error Converting from Datetime Character String

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

Resources