Search by Image with SQL Server database and VB - sql-server

I am tired to make the search engine to run. Just I want to make search by image in my SQL Server database by making a choice of the column with same image.
I tried to make it with this code:
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
Can anyone help me?
Picture of Project
This is my code
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Image
Public Class Form1
Dim sqlcon As New SqlConnection("server=.\MOHAMED; database=DB_Image;
integrated security = true")
Dim cmd As SqlCommand
Sub selectImage(ByVal Image As Image)
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
sqlcon.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
dr.Read()
txtShow.Text = dr(0)
Dim sora2() As Byte = CType(dr(1), Byte())
Dim ms2 As New MemoryStream(sora2)
pbox3.Image = Image.FromStream(ms2)
dr.Read()
Dim sora3() As Byte = CType(dr(1), Byte())
Dim ms3 As New MemoryStream(sora3)
pbox4.Image = Image.FromStream(ms3)
dr.Read()
Dim sora4() As Byte = CType(dr(1), Byte())
Dim ms4 As New MemoryStream(sora4)
pbox5.Image = Image.FromStream(ms4)
dr.Read()
Dim sora5() As Byte = CType(dr(1), Byte())
Dim ms5 As New MemoryStream(sora5)
pbox6.Image = Image.FromStream(ms5)
dr.Read()
Dim sora6() As Byte = CType(dr(1), Byte())
Dim ms6 As New MemoryStream(sora6)
pbox7.Image = Image.FromStream(ms6)
dr.Read()
Dim sora7() As Byte = CType(dr(1), Byte())
Dim ms7 As New MemoryStream(sora7)
pbox8.Image = Image.FromStream(ms7)
sqlcon.Close()
dr.Close()
End Sub
Private Sub btnBrowse1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse1.Click
ofd1.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd1.ShowDialog = DialogResult.OK Then
pbox1.Image = Image.FromFile(ofd1.FileName)
End If
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
cmd = New SqlCommand("Insert into TBL_Image(Description, Image) values(#Description, #Image)", sqlcon)
cmd.Parameters.Add(New SqlParameter("#Description", SqlDbType.Text)).Value = txtDescription.Text
Dim ms1 As New MemoryStream
pbox1.Image.Save(ms1, pbox1.Image.RawFormat)
Dim Image() As Byte = ms1.ToArray
cmd.Parameters.Add(New SqlParameter("#Image", SqlDbType.Image)).Value = Image
sqlcon.Open()
cmd.ExecuteNonQuery()
sqlcon.Close()
MsgBox("Added successfully")
End Sub
Private Sub btnBrowse2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse2.Click
ofd2.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd2.ShowDialog = DialogResult.OK Then
pbox2.Image = Image.FromFile(ofd2.FileName)
End If
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim msnew As New MemoryStream
pbox2.Image.Save(msnew, pbox2.Image.RawFormat)
Dim Image() As Byte = msnew.ToArray
selectImage(pbox2.Image)
End Sub
End Class

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

Value cannot be NULL when saving DataGridView to SQL dB

I have a form with a datagridview (ViewCustomersForm) and a save button.
What I am trying to do is get the user to edit the infotmation in the datagrid view and then hit a save button, which will save the values back to my SQL table.
Unfortunately though, when my save button is pressed I get the following error.
"Value cannot be null."
Pointing at this line of code:
dataadapter.Update(ds.Tables("Customers_table"))
In the context of the below code:
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Customers._Customers' table. You can move, or remove it, as needed.
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim ds As DataSet = New DataSet()
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim ds As DataSet = New DataSet()
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
I am relatively new to VB, so any help or pointers greatly appreciated.
Thanks
I needed to have by variables defined at the Class level, not with in the Subs.
Here is the working code.
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Private Sub Button1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
End Class

How to permanently delete a record of database from VB

Im a beginner in VB and Im trying to delete a record from a database but it doesnt let me...
they gave me this error message which i do not fully understand what it meant...
or is there any other way to delete the record permanently?
Column named userID cannot be found.
Parameter name: columnName
Heres my codes
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class frmUserManagement
Dim countID As Integer = 0
Dim conn As New SqlConnection
Dim drEmployee As SqlClient.SqlDataReader
Dim cmdEmployee As New SqlClient.SqlCommand
Dim sAdapter As New SqlDataAdapter
Dim sTable As New DataTable
Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
Dim tranEmployee As SqlClient.SqlTransaction
sAdapter = New SqlDataAdapter(cmdEmployee)
Dim strID As String
Dim strName As String
Dim strPosition As String
Dim strContactNo As String
Dim strAddress As String
Dim strDOB As String
Dim strGender As String
Dim strSQL As String
conn.Open()
strID = lblEmpID.Text
strName = txtEmpName.Text
strPosition = cboEmpPosition.Text
strContactNo = mskEmpDOB.Text
strDOB = mskEmpDOB.Text
strAddress = txtEmpAddress.Text
If radEmpMale.Checked Then
strGender = "Male"
Else
strGender = "Female"
End If
strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
"VALUES(#ID,#NAME,#POSITION,#GENDER,#DOB,#ADDRESS)"
tranEmployee = conn.BeginTransaction()
With cmdEmployee
.Transaction = tranEmployee
.CommandText = strSQL
.Parameters.AddWithValue("#ID", strID)
.Parameters.AddWithValue("#NAME", strName)
.Parameters.AddWithValue("#POSITION", strPosition)
.Parameters.AddWithValue("#GENDER", strGender)
.Parameters.AddWithValue("#DOB", strDOB)
.Parameters.AddWithValue("#ADDRESS", strAddress)
.Connection = conn
End With
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub frmUserManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If mintIndex <= 9000 Then
lblEmpID.Text = "EMP" & (countID + 1).ToString("000#")
End If
Try
With conn
.ConnectionString = strConnection
.Open()
End With
With cmdEmployee
.CommandText = "SELECT * FROM Users ORDER BY userID"
.Connection = conn
End With
drEmployee = cmdEmployee.ExecuteReader()
If drEmployee.HasRows Then
While drEmployee.Read()
DataGridView1.Rows.Add(drEmployee(0), drEmployee(3), drEmployee(1), drEmployee(4), drEmployee(2), drEmployee(5))
End While
drEmployee.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub btnDeleteEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteEmp.Click
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = " & DataGridView1.CurrentRow.Cells(0).Value & ""
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With
Dim rows = DataGridView1.SelectedRows
For Each row In rows
cmdEmployee.Parameters("#ID").Value = row.Cells("userID").Value
cmdEmployee.ExecuteNonQuery()
Next
drEmployee = cmdEmployee.ExecuteReader()
End Sub
Private Sub btnEditEmp_Click(sender As System.Object, e As System.EventArgs) Handles btnEditEmp.Click
lblEmpID.Enabled = False
txtEmpName.Enabled = False
grpGender.Enabled = False
End Sub
End Class
It means you do not have a column named userID in your table, are you sure it's not just ID?
You should use:
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = #ID"
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With

How to declare a connection object on a class level connection not in local scope with VB.NET?

I got the error:
Fill: SelectCommand.Connection property has not been initialized.
I think this is because I declare my data set not inside the private sub but in the public class.....
but I need to use the data set in more than once in different private sub during the program....how should I define it ?
many thanks.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim strsql As String
Dim da As New SqlDataAdapter(strsql, con)
Dim ds As New DataSet()
Dim strcon As String
Dim newmode As Boolean
Dim newrow As DataRow
Dim cb As SqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
'Dim con As SqlConnection
'Dim strsql As String
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
'Dim da As New SqlDataAdapter(strsql, con)
'Dim ds As New DataSet()
da.Fill(ds, "dd")
TextBox1.DataBindings.Add(New Binding("text", ds, "dd.tel"))
TextBox2.DataBindings.Add(New Binding("text", ds, "dd.nam"))
TextBox3.DataBindings.Add(New Binding("text", ds, "dd.address"))
da.update(ds, "dd")
con.Close()
End Sub
Private Sub empty()
textrecord.text = ""
TextBox1.text = ""
TextBox2.text = ""
TextBox3.text = ""
TextBox4.text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newrow = ds.Tables("dd").NewRow
newmode = True
textrecord.BackColor = Color.Red
textrecord.Text = "new record"
MsgBox("enter new record and press save")
Call empty()
End Sub
End Class
Instead of:
Dim con As SqlConnection
try adding New:
Dim con As New SqlConnection("initial catalog=test;...")
However, it's best practice to only open a connection just before you need it, and close it right after. Connections should be local variables in Using blocks, not class variables!
You create the DataAdapter at the global level in this line
Dim da As New SqlDataAdapter(strsql, con)
but at this point in time your strsql is empty and if you change it afterwards it doesn't change inside the dataadatpter, thus the error message.
If you insist on keeping all that global vars (and it's considered a bad practice as #Andomar pointed out in is answer) then you should be sure to create the DataAdapter with the correct sqlstring just before its usage:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
da = New SqlDataAdapter(strsql, con) '<- added this line here '
da.Fill(ds, "dd")
....
con.Close()
End Sub

Resources