How to edit and delete rows of a database using ASP? - sql

I currently have a website that displays all the data within the database
Dim dcSQL As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("College").ConnectionString)
Dim dbAdapt As New System.Data.SqlClient.SqlDataAdapter()
Dim cmd As New SqlCommand("SELECT * FROM [College].[dbo].[Class]", dcSQL)
dbAdapt.SelectCommand = cmd
Dim ds As New DataSet
dbAdapt.Fill(ds)
If dbAdapt IsNot Nothing Then
gvStudents0.DataSource = ds.Tables(0)
gvStudents0.DataBind()
End If
Catch ex As Exception
End Try
End Sub'
But I want to create/edit and delete the database, I am aware of how to do this in EF but I am currently not aware in SQL, can someone help?

The following snippet is from SqlCommand.Parameters Property .
Updating
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = #demographics " _
& "WHERE CustomerID = #ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
' Use AddWithValue to assign Demographics.
' SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml)
Try
connection.Open()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Deleting
For deleting the command could be as follows.
Dim commandText As String = _
"DELETE FROM Sales.Store WHERE CustomerID = #ID;"
(...)
command.Parameters.Add("#CustomerID ", SqlDbType.Int).Value = xxx;
Inserting
For inserting the sql will be something like the following
Dim commandText As String = _
"INSERT INTO tablename(column1,column2,column3)" _
& " VALUES(#column1,#column2,#column3);"
and then
command.Parameters.Add("#column1", SqlDbType.Int).Value = x;
command.Parameters.Add("#column2", SqlDbType.Int).Value = y;
command.Parameters.Add("#column3", SqlDbType.Int).Value = z;
or
command.Parameters.AddWithValue("#column1", x);
command.Parameters.AddWithValue("#column2", y);
command.Parameters.AddWithValue("#column3", z)
Please note that this is not ASP.NET specific. A console app could use this code as well.

You can use this class that I make and don’t care about SQL (in some cases).
You can just pas lists (Of String) as parameter and the methods do the tasks.
Imports System.Data.SqlClient
Friend Class SqlDB
Friend Property _SConessione As String = ""
Private _NomeDB As String = ""
Private _SQLConnection As SqlConnection
Private _SQLCommand As SqlCommand
Private _SQLAdapter As SqlDataAdapter
Private _SQLReader As SqlDataReader
Friend Enum Version
SQL_SERV_2005 = 90
SQL_SERV_2008 = 100
SQL_SERV_2012 = 110
End Enum
Friend Structure Inputs
Const _CHAR As String = "CHAR"
Const _VARCHAR As String = "VARCHAR"
Const _TEXT As String = "TEXT"
Const _NCHAR As String = "NCHAR"
Const _NVARCHAR As String = "NVARCHAR"
Const _NTEXT As String = "NTEXT"
Const _BIT As String = "BIT"
Const _BINARY As String = "BINARY"
Const _VARBINARY As String = "VARBINARY"
Const _IMAGE As String = "IMAGE"
Const _TINYINT As String = "TINYINT"
Const _SMALLINT As String = "SMALLINT"
Const _BIGINT As String = "BIGINT"
Const _DECIMAL As String = "DECIMAL(10,2)"
Const _NUMERIC As String = "NUMERIC(10)"
Const _FLOAT As String = "FLOAT"
Const _DATE As String = "DATE"
Const _DATETIME As String = "DATETIME"
End Structure
Friend Structure NULLS
Const NULL = "NULL"
Const NOT_NULL = "NOT NULL"
End Structure
Friend Structure Cols
Dim Nome As String
Dim TInput As String
Dim Length As Integer
Dim Null As String
End Structure
Private _Versione As Version = Version.SQL_SERV_2008
Friend Function SqlDate(dateStr As String) As String
If IsDate(dateStr) Then
Dim sDate As String = ""
dateStr = CDate(dateStr).ToShortDateString
sDate = " CONVERT(DATE, '" & dateStr & "', 0) "
Return sDate
Else
Throw New Exception("Formato data non valido")
End If
Return ""
End Function
Friend Property Versione As Version
Get
Return _Versione
End Get
Set(value As Version)
_Versione = value
End Set
End Property
Friend Enum TypeIndex
CLUSTER = 0
NONCOLUSTER = 1
End Enum
Friend Sub New(ByVal ConString As String,
ByVal VersionServer As Version)
Try
Versione = VersionServer
If ConString.Length > 0 Then
_SConessione = ConString
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
End Sub
Friend Sub New(ByVal ConString As String)
Try
Versione = _Versione
If ConString.Length > 0 Then
_SConessione = ConString
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
End Sub
Friend Function ExecuteRestore(Optional ByVal pathBackup As String = "", Optional NameDb As String = "") As Boolean
Dim res As Boolean = False
If NameDb.Length > 0 Then _NomeDB = NameDb
If _NomeDB.Length = 0 Then
Debug.WriteLine("Set the name of DB")
Return False
End If
Dim Sql = " USE [master]; " & vbCrLf
Sql &= " RESTORE DATABASE [" & _NomeDB & "]" & vbCrLf
Sql &= " FROM DISK = '" & pathBackup & "'" & vbCrLf
Sql &= " WITH FILE = 1, NOUNLOAD, REPLACE" & vbCrLf '
Try
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
res = CBool(command.ExecuteNonQuery())
res = True
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return res
End Function
Friend Function ExecuteQuery(sql As String) As Boolean
Dim res As Boolean = False
If sql.Length > 0 Then
sql = "USE [" & _NomeDB & "]; " & vbCrLf & sql
End If
Try
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(sql, SQLConnection)
command.ExecuteNonQuery()
End Using
Return True
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return res
End Function
Friend Function ReadTheFirstResult(sql As String) As Object
Dim sRet As Object = ""
If sql.Length > 0 Then
sql = "USE [" & _NomeDB & "]; " & vbCrLf & sql
End If
Try
Dim SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(sql, SQLConnection)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read
sRet = reader(0)
Exit While
End While
Catch ex As SqlException
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return sRet
End Function
Friend Function GetDataAsDataReader(Sql As String, Optional ByRef RowsCount As Integer = -1) As SqlDataReader
Dim reader As SqlDataReader = Nothing
If Sql.Length > 0 Then
Sql = "USE [" & _NomeDB & "]; " & vbCrLf & Sql
End If
Try
Dim SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
If RowsCount > -1 Then
Dim DtTable As New DataTable
Dim mSqlAdapter As New SqlClient.SqlDataAdapter With {
.SelectCommand = New SqlCommand(Sql, SQLConnection)
}
mSqlAdapter.Fill(DtTable)
RowsCount = DtTable.Rows.Count
End If
Dim command As New SqlCommand(Sql, SQLConnection)
reader = command.ExecuteReader()
Catch ex As SqlException
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return reader
End Function
Friend Function CheckOrCreateDB(ByVal dbName As String) As Boolean
Try
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [master]; ")
query.Append("IF NOT EXISTS(SELECT * FROM sys.databases Where name = '" & dbName & "') ")
query.Append(" CREATE DATABASE [" & dbName & "] ")
query.Append(" ALTER DATABASE [" & dbName & "] SET COMPATIBILITY_LEVEL = " & Versione & " ;")
query.Append(" ALTER DATABASE [" & dbName & "] SET READ_WRITE ;")
query.Append(" ALTER DATABASE [" & dbName & "] SET MULTI_USER ;")
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
_NomeDB = dbName
End Using
Return True
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
_NomeDB = ""
Return False
End Try
End Function
Friend Function CheckOrCreateTable(ByVal tableName As String, ByVal columns As List(Of Cols)) As Boolean
Try
If _NomeDB IsNot Nothing AndAlso _NomeDB.Length > 0 Then
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS ( SELECT * FROM sys.tables WHERE name = '" & tableName & "' ) ")
query.Append(" CREATE TABLE " & tableName & " ")
query.Append(" ( IndexRow INT IDENTITY(1,1) NOT NULL ); ")
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
End Using
query.Clear()
If columns IsNot Nothing AndAlso columns.Count > 0 Then
For i As Integer = 0 To columns.Count - 1
Dim TipoInput As String = columns(i).TInput & " "
If columns(i).Length > 0 Then
CreateColumn(tableName, columns(i).Nome, TipoInput, columns(i).Null, CStr(columns(i).Length))
Else
CreateColumn(tableName, columns(i).Nome, TipoInput, columns(i).Null)
End If
Next
End If
Return True
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return False
End Function
Friend Function CreateColumn(ByVal tableName As String,
ByVal columnName As String,
ByVal TipoInput As String,
ByVal nullOrNot As String,
Optional ByVal Lunghezza As String = "-1") As Integer
Dim i As Integer = 0
Try
Dim mTipoInput As String = TipoInput
If CInt(Lunghezza) > -1 Then mTipoInput = mTipoInput & "(" & Lunghezza & ") "
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('" & tableName & "') AND name = '" & columnName & "' )")
query.Append(" ALTER TABLE " & tableName)
query.Append(" ADD " & columnName & " " & mTipoInput & " " & nullOrNot)
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
i = command.ExecuteNonQuery()
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return i
End Function
Friend Function CheckOrCreateColumn(ByVal tableName As String,
ByVal columnName As String,
Optional ByVal inputType As String = Inputs._VARCHAR,
Optional ByVal nullOrNot As String = "NULL",
Optional ByVal Lunghezza As String = "-1") As Integer
Dim i As Integer = 0
Try
Dim mTipoInput As String = inputType
If CInt(Lunghezza) > -1 Then mTipoInput = mTipoInput & "(" & Lunghezza & ") "
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('" & tableName & "') AND name = '" & columnName & "' )")
query.Append(" ALTER TABLE " & tableName)
query.Append(" ADD " & columnName & " " & mTipoInput & " " & nullOrNot)
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
i = command.ExecuteNonQuery()
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return i
End Function
Friend Function CheckOrCreateIndex(tipo As TypeIndex,
indexName As String,
tableName As String,
columnsIndexes() As String,
Optional includedColumns() As String = Nothing) As String
Dim res As String = ""
Try
' CREATE INDEX IX_TableName_Col1
' ON dbo.TableName
' (column_1)
If columnsIndexes.Length > 0 Then
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT name FROM sys.indexes WHERE name = '" & indexName & "')")
Select Case tipo
Case TypeIndex.CLUSTER
query.Append(" CREATE CLUSTERED INDEX " & indexName)
Case TypeIndex.NONCOLUSTER
query.Append(" CREATE NONCLUSTERED INDEX " & indexName)
End Select
query.Append(" ON [" & tableName & "] (" & JoinParams(columnsIndexes, False).Trim & ")")
If includedColumns IsNot Nothing AndAlso includedColumns.Length > 0 Then
query.Append(" Include (" & JoinParams(includedColumns, False) & ")")
End If
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
res = indexName
End Using
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
'Debugger.Break()
#End If
End Try
Return res
End Function
Friend Function InsertInto(tableName As String, listOfCols As List(Of String), listOfValues As List(Of String)) As Boolean
Try
Dim Sql As String = " USE [" & _NomeDB & "]; "
Sql &= " INSERT INTO " & tableName
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
Sql &= " (" & Join(listOfCols.ToArray, ",") & ")"
Sql &= " VALUES (" & JoinParams(listOfValues.ToArray) & ")"
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
command.ExecuteNonQuery()
End Using
Return True
End If
Catch ex As Exception
#If DEBUG Then
Console.WriteLine(ex.ToString)
'Stop
#End If
End Try
Return False
End Function
Friend Function UpdateInto(tableName As String, listOfCols As List(Of String), listOfValues As List(Of String), WhereClausola As String) As Integer
Dim ret As Integer = 0
Try
Dim Sql As String = " USE [" & _NomeDB & "]; "
Sql &= " UPDATE " & tableName & " SET "
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
' UPDATE Customers
'SET
'ContactName ='Alfred Schmidt',
'City ='Hamburg'
'WHERE CustomerName ='Alfreds Futterkiste';
For i As Integer = 0 To listOfCols.Count - 1
Sql &= " " & listOfCols(i) & "=" & CStr(IIf(listOfValues(i) IsNot Nothing, listOfValues(i), "NULL")) & CStr(IIf(i < listOfCols.Count - 1, ",", ""))
Next
If WhereClausola IsNot Nothing AndAlso WhereClausola.Length > 0 Then
WhereClausola = WhereClausola.ToLower.Replace("where", " ")
Sql &= " WHERE " & WhereClausola
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
ret = command.ExecuteNonQuery()
End Using
End If
End If
End If
Return ret
Catch ex As Exception
#If DEBUG Then
Console.WriteLine(ex.ToString)
'Stop
#End If
End Try
Return ret
End Function
Private Function JoinParams(ByVal params() As String, Optional ByVal UseVbcrlf As Boolean = True) As String
Dim s As String = ""
Dim mVbCrlf As String = CStr(IIf(UseVbcrlf, vbCrLf, " "))
For i As Integer = 0 To params.Length - 1
If params(i) IsNot Nothing Then
If i = params.Length - 1 Then
s &= params(i) & " " & mVbCrlf
Else
s &= params(i) & ", " & mVbCrlf
End If
End If
Next
Return s
End Function
Friend Sub Open(sqlConn As SqlConnection)
Try
_SQLConnection = sqlConn
Select Case sqlConn.State
Case <> ConnectionState.Connecting
sqlConn.Close()
sqlConn.ConnectionString = _SConessione
sqlConn.Open()
End Select
Catch ex As Exception
End Try
End Sub
Friend Sub Close()
Try
If _SQLConnection IsNot Nothing Then
_SQLConnection.Close()
End If
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
End Sub
End Class
Module SQLUtil
Function InLIKE(s As String) As String
'%email pippo%
If s IsNot Nothing AndAlso s.Length > 0 Then
Return "%" & s & "%"
End If
Return "%%"
End Function
Function InApice(value As String) As String
If value Is Nothing Then Return "''"
If value.Length = 0 Then Return "''"
Dim appice As String = "'" '"`"
value = value.Replace("'", "''")
Return " " & appice & value & appice & " "
End Function
Function ToDate(dateStr As String) As String
If IsDate(dateStr) Then
Dim sDate As String = CDate(dateStr).ToString
Return sDate
End If
Return dateStr
End Function
Function ToDbDate(dateStr As String) As String
dateStr = New Date(dateStr)
If IsDate(dateStr) Then
Dim mDate As Date = CDate(dateStr)
Dim anno As Integer = mDate.Year
Dim mese As Integer = mDate.Month
Dim giorno As Integer = mDate.Day
Dim ora As Integer = mDate.Hour
Dim minuto As Integer = mDate.Minute
If Not IsNumeric(anno) Then anno = 0
If Not IsNumeric(mese) Then mese = 0
If Not IsNumeric(giorno) Then giorno = 0
If Not IsNumeric(ora) Then ora = 0
If Not IsNumeric(minuto) Then minuto = 0
anno = Strings.Format(anno, "0000")
mese = Strings.Format(mese, "00")
giorno = Strings.Format(giorno, "00")
ora = Strings.Format(ora, "00")
minuto = Strings.Format(minuto, "00")
Dim sDate As String = CStr(anno) & CStr(mese) & CStr(giorno) & CStr(ora) & CStr(minuto)
Return sDate
End If
Return ""
End Function
Function FromDbDate(s As String, Optional ancheOraEMinuti As Boolean = False) As String
If s Is Nothing Then Return ""
If s.Length = 0 Then Return ""
If s.Length > 12 Then
Dim data As String = ""
Dim anno As String = s.Substring(0, 4)
Dim mese As String = s.Substring(5, 2)
Dim giorno As String = s.Substring(7, 2)
Dim ora As String = s.Substring(9, 2)
Dim minuti As String = s.Substring(11, 2)
End If
Return ""
End Function
End Module

Related

The Connection String Property Has Not Been Initialized vb.net

Please can you tell me why my database info is not pulling through. i am fearly new to vb and i have been trying to create this project with the help of google but stuck on linking my db
Imports System.Data.OleDb
Public Class MyeventDB
Public Shared Function GetEvent(eventID As Integer) As Myevent
Dim myevent As New Myevent
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim selectStatement As String =
"SELECT EventID, Title, Date, Fee, Location, Distance " &
"FROM Events " &
"WHERE EventID = #EventID"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
selectCommand.Parameters.AddWithValue("#EventID", eventID)
Try
connection.Open()
Dim reader As OleDbDataReader _
= selectCommand.ExecuteReader(CommandBehavior.SingleRow)
If reader.Read Then
myevent.EventID = CInt(reader("EventID"))
myevent.Title = reader("Title").ToString
myevent.DDate = reader("Date").ToString
myevent.Fee = reader("Fee").ToString
myevent.Location = reader("Location").ToString
myevent.Distance = reader("Distance").ToString
Else
myevent = Nothing
End If
reader.Close()
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
Return myevent
End Function
Public Shared Function AddEvent(myevent As Myevent) As Integer
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim insertStatement As String =
"INSERT Events " &
"(Title, Date, Fee, Location, Distance) " &
"VALUES (#Title, #Date, #Fee, #Location, #Distance)"
Dim insertCommand As New OleDbCommand(insertStatement, connection)
insertCommand.Parameters.AddWithValue("#Title", myevent.Title)
insertCommand.Parameters.AddWithValue("#Date", myevent.DDate)
insertCommand.Parameters.AddWithValue("#Fee", myevent.Fee)
insertCommand.Parameters.AddWithValue("#Location", myevent.Location)
insertCommand.Parameters.AddWithValue("#Distance", myevent.Distance)
Try
connection.Open()
insertCommand.ExecuteNonQuery()
Dim selectStatement As String _
= "SELECT IDENT_CURRENT('Events') FROM Events"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
Dim eventID As Integer = CInt(selectCommand.ExecuteScalar)
Return eventID
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
Public Shared Function UpdateEvent(oldEvent As Myevent,
newEvent As Myevent) As Boolean
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim updateStatement As String =
"UPDATE Events SET " &
"Title = #NewTitle, " &
"Date = #NewDate, " &
"Fee = #NewFee, " &
"Location = #NewLocation, " &
"Distance = #NewDistance " &
"WHERE EventID = #OldEventID " &
"AND Title = #OldTitle " &
"AND Date = #OldDate " &
"AND Fee = #OldFee " & "AND Location = #OldLocation " &
"AND Distance = #OldDistance"
Dim updateCommand As New OleDbCommand(updateStatement, connection)
updateCommand.Parameters.AddWithValue("#NewTitle", newEvent.Title)
updateCommand.Parameters.AddWithValue("#NewDate", newEvent.DDate)
updateCommand.Parameters.AddWithValue("#NewFee", newEvent.Fee)
updateCommand.Parameters.AddWithValue("#NewLocation", newEvent.Location)
updateCommand.Parameters.AddWithValue("#NewDistance", newEvent.Distance)
updateCommand.Parameters.AddWithValue("#OldEventID", oldEvent.EventID)
updateCommand.Parameters.AddWithValue("#OldTitle", oldEvent.Title)
updateCommand.Parameters.AddWithValue("#OldDate", oldEvent.DDate)
updateCommand.Parameters.AddWithValue("#OldFee", oldEvent.Fee)
updateCommand.Parameters.AddWithValue("#OldLocation", oldEvent.Location)
updateCommand.Parameters.AddWithValue("#OldDistance", oldEvent.Distance)
Try
connection.Open()
Dim count As Integer = updateCommand.ExecuteNonQuery
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
Public Shared Function DeleteEvent(myevent As Myevent) As Boolean
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim deleteStatement As String =
"DELETE FROM Events " &
"WHERE EventID = #EventID " &
"AND Title = #Title " &
"AND Date = #Date " &
"AND Fee = #Fee " &
"AND Location = #Location " &
"AND Distance = #Distance"
Dim deleteCommand As New OleDbCommand(deleteStatement, connection)
deleteCommand.Parameters.AddWithValue("#EventID", myevent.EventID)
deleteCommand.Parameters.AddWithValue("#Title", myevent.Title)
deleteCommand.Parameters.AddWithValue("#Date", myevent.DDate)
deleteCommand.Parameters.AddWithValue("#Fee", myevent.Fee)
deleteCommand.Parameters.AddWithValue("#Location", myevent.Location)
deleteCommand.Parameters.AddWithValue("#Distance", myevent.Distance)
Try
connection.Open()
Dim count As Integer = deleteCommand.ExecuteNonQuery
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
End Class
Imports System.Data.OleDb
Public Class MyAthleteEvents
Public Shared Function GetConnection() As OleDbConnection
' If necessary, change the following connection string
' so it works for your system
Dim connectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\lebom\Desktop\ICT3611Assignment\AthletesEvents.accdb")
Return New OleDbConnection()
End Function
End Class
In your MyAthleteEvents.GetConnection, you create one OleDbConnection object with a connection string but then, instead of returning that object, you return a second new OleDbConnection object.
This:
Return New OleDbConnection()
should be this:
Return connectionString
That said, why would you use the name 'connectionString' for a variable of type OleDbConnection? It's not a connection string so why name it as though it is? It would have to be a String to be a connection string.

Code getting stuck in BackgroundWorker

Am having a problem with a BackgroundWorker getting stuck.
have thrown in loads of console.writeline's to help try and narrow down where the issue is, but am getting nowhere fast.
I noticed when going back through the output, I have this message...
The thread 0x2d68 has exited with code 259 (0x103)
Can anyone tell me what that means?
EDIT - Below is my full code.
To give some background, this app is processing requested received from a website to deploy a virtual machine in a cloud environment.
It works fine for the first few items, but then it gets stuck inside the "BuildProgressCheck" BackgroundWorker.
It then stops processing any more items and the BuildProgressCheck Backgroundworker isbusy sticks at true.
Any help appriciated, I've been trying to solve this for a while now. :(
Thanks!
Imports MySql.Data.MySqlClient
Imports System
Imports System.IO
Imports System.Xml
Imports System.Net.Mail
Imports System.Text
Imports System.Diagnostics
Public Class Home
Public dbserver As String
Public dbusername As String
Public dbpassword As String
Public dbdatabase As String
Public appdebug As String
Public appconfig As String
Public jobcheckresult As String = "jobcheckresult"
Public buildchecktickid As Integer = 0
Public jobchecktickid As Integer = 0
Public new_vm_jobid As String
Public new_vm_state As String
Public new_vm_ipaddress As String
Public new_vm_macaddress As String
Public new_vm_hostname As String
Public new_vm_cpunumber As String
Public new_vm_cpuspeed As String
Public new_vm_memory As String
Public new_vm_netmask As String
Public new_vm_gateway As String
Public new_vm_templatename As String
Public new_vm_instancename1 As String
Public job_check_status As String
Public jobcheckstatusid As String
Public new_vm_success_internal_email As String
Public new_vm_fail_internal_email As String
Public new_vm_success_external_email As String
Public new_vm_processing_internal_email As String
Public internal_email_recipient As String
Public internal_email_sender As String
Public internal_mail_server As String
Public internal_mail_server_username As String
Public internal_mail_server_password As String
Public logentrytext As String
Public logdirectory As String = "C:\CloudPlatform\"
Public logpath As String = logdirectory & "dbcpman_log.txt"
Public logappend As Boolean = True
Public ccnl = ControlChars.NewLine
Public cpapiurl As String = "http://192.168.16.221:8081/client/api?"
Public cpapikey As String = "apiKey=YUsTgg_d6QB9KhdjYS6K314t9BZhL0B3T-DHR1vm8BrkF2pv2qqx698Vzb8O-srSOAKYa0nYB8qLQdXjaKHefQ"
Public buildcheckactive As Integer = 0 ' 0=false, 1=true '
Public buildprogresscheckactive As Integer = 0 ' 0=false, 1=true '
Public jobcheckactive As Integer = 0 ' 0=false, 1=true '
Public Sub login_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown
Control.CheckForIllegalCrossThreadCalls = False
Dim config As String = "cloudcommander.conf"
If System.IO.File.Exists(config) = True Then
Dim objReader As New System.IO.StreamReader(config)
appconfig = objReader.ReadToEnd
objReader.Close()
Dim configlines() As String = appconfig.Split(vbCrLf)
For Each line As String In configlines
' MessageBox.Show(configlines)
Next
dbserver = configlines(1)
dbserver = Replace(dbserver, "server=", "")
dbdatabase = configlines(2)
dbdatabase = Replace(dbdatabase, "database=", "")
dbusername = configlines(3)
dbusername = Replace(dbusername, "userid=", "")
dbpassword = configlines(4)
dbpassword = Replace(dbpassword, "password=", "")
Else
lblstatus.Text = "Configuration Error"""
MsgBox("Could not locate configuration file " & ControlChars.NewLine & ControlChars.NewLine & "This program may not work correctly :(")
End If
lblstatus.Text = "Configuration is fine - moving along..."
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE failed='false'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim row As DataRow
For Each row In jobcheck_table.Rows
Dim strDetail As String
strDetail = row("dbxid")
buildpendinglist.Items.Add(strDetail)
logentrytext = "[STARTUP] Found pending job for import: " & strDetail
Call dbcpman_log(logentrytext, logdirectory, logpath, logappend) ''''''Do some logging
Next row
Try
logentrytext = "[JOB-CALLBACK] API response: " & jobcheckresult
Call dbcpman_log(logentrytext, logdirectory, logpath, logappend) ''''''Do some logging
Catch ex As Exception
End Try
BuildWorkerTimer.Start()
BuildProgressCheckTimer.Start()
End Sub
Private Sub NewItemCheck_Tick(sender As Object, e As EventArgs) Handles BuildWorkerTimer.Tick
buildchecktickid = buildchecktickid + 1
countbuilds.Text = buildcheckactive
countjobs.Text = buildprogresscheckactive
If BuildWorker.IsBusy Then
Beep()
Else
BuildWorker.RunWorkerAsync()
End If
End Sub
Private Sub BuildProgressCheckTimer_Tick(sender As Object, e As EventArgs) Handles BuildProgressCheckTimer.Tick
Console.WriteLine("Timer 'BuildProgressCheckTimer'.... TICK!")
Dim bpc_busy_count As Integer = 0
If BuildProgressCheck.IsBusy Then
Beep()
bpc_busy_count = bpc_busy_count + 1
If bpc_busy_count > 4 Then
Beep()
Beep()
BuildProgressCheck.CancelAsync()
End If
Else
BuildProgressCheck.RunWorkerAsync()
End If
End Sub
Private Sub BuildWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BuildWorker.DoWork
lblstatus.Text = "Checking for new requests"
buildcheckactive = 1
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim vmcheck As New MySqlDataAdapter("Select * FROM dbcpman_vm WHERE deployrequired='true' ", cn)
Dim vmcheck_table As New DataTable
vmcheck.Fill(vmcheck_table)
Dim row As DataRow
row = vmcheck_table.Select("deployrequired = 'true'").FirstOrDefault()
If Not row Is Nothing Then
Dim new_vm_id As String = row.Item("id")
Dim new_vm_account As String = row.Item("account")
Dim new_vm_name As String = row.Item("name")
Dim new_vm_displayname As String = row.Item("displayname")
Dim new_vm_memory As String = row.Item("memory")
Dim new_vm_cpuspeed As String = row.Item("cpuspeed")
Dim new_vm_cpunumber As String = row.Item("cpunumber")
Dim new_vm_group As String = row.Item("vmgroup")
Dim new_vm_instancename As String = row.Item("instancename")
Dim new_vm_diskofferingid As String = row.Item("diskofferingid")
Dim new_vm_disksize As String = row.Item("customdisksize")
Dim new_vm_serviceofferingid As String = row.Item("serviceofferingid")
Dim new_vm_serviceofferingname As String = row.Item("serviceofferingname")
Dim new_vm_publicip As String = row.Item("publicip")
Dim new_vm_os As String = row.Item("OS")
Dim new_vm_templateid As String = row.Item("templateid")
Dim dbx_id As String = row.Item("dbx_id")
Dim new_job_status As String = "NEW"
dbx_id = dbx_id & new_vm_id
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET dbx_id = '" & dbx_id & "' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Catch ex As Exception
MessageBox.Show("ERROR3 " & ccnl & ccnl & ex.Message)
End Try
buildpendinglist.Items.Add(dbx_id)
Dim commandstring As String = "command=deployVirtualMachine" _
& "&ServiceOfferingId=" & new_vm_serviceofferingid _
& "&size=" & new_vm_disksize _
& "&templateId=" & new_vm_templateid _
& "&zoneid=1" _
& "&displayname=" & new_vm_displayname _
& "&name=" & new_vm_name _
& "&instancename=" & new_vm_instancename _
& "&internalname=" & new_vm_displayname
Dim fullapiurl = cpapiurl & commandstring
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET deployrequired = 'false' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Catch ex As Exception
MessageBox.Show("ERROR2 " & ccnl & ccnl & ex.Message)
End Try
Try
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(fullapiurl)
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(result)
Dim new_vm_jobidxml = doc.GetElementsByTagName("jobid")
For Each item As System.Xml.XmlElement In new_vm_jobidxml
new_vm_jobid = item.ChildNodes(0).InnerText()
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET deploy_jobid = '" & new_vm_jobid & "' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET deploycompleted = 'false' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "INSERT into dbcpman_jobs(jobid, status, dbxid) VALUES ('" & new_vm_jobid & "','" & new_job_status & "','" & dbx_id & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
'MessageBox.Show("ADDED ITEM TO JOBS")
Next
Catch ex As Exception
MessageBox.Show("ERROR1 " & ccnl & ccnl & ex.Message)
End Try
End If
new_vm_jobid = ""
new_vm_state = ""
new_vm_ipaddress = ""
new_vm_macaddress = ""
new_vm_hostname = ""
new_vm_cpunumber = ""
new_vm_cpuspeed = ""
new_vm_memory = ""
new_vm_netmask = ""
new_vm_gateway = ""
new_vm_templatename = ""
new_vm_instancename1 = ""
buildcheckactive = 0
End Sub
Private Sub BuildProgressCheck_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BuildProgressCheck.DoWork
Dim i As Integer
For i = 0 To buildpendinglist.Items.Count - 1
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE dbxid='" & buildpendinglist.Items(i) & "'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim jobrow As DataRow
jobrow = jobcheck_table.Select("failed = 'false'").FirstOrDefault()
If Not jobrow Is Nothing Then
Dim job_id As String = jobrow.Item("id")
Dim job_jobid As String = jobrow.Item("jobid")
Dim job_status As String = jobrow.Item("status")
Dim job_dbxid As String = jobrow.Item("dbxid")
Dim jobcommand As String = "command=queryAsyncJobResult&jobId=" & job_jobid
Dim fulljobapicheckurl = cpapiurl & jobcommand
Try
Dim jobapicall As New System.Net.WebClient
jobcheckresult = jobapicall.DownloadString(fulljobapicheckurl)
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-1' - Error during API call")
End Try
If jobcheckresult.Contains("<jobstatus>1</jobstatus>") Then ''If true, job has completed
Console.WriteLine(job_dbxid & "Is completed")
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(jobcheckresult) ''api_result contains xml returned from a http request.
Try
Console.WriteLine("Entering XML Parse...")
If doc.GetElementsByTagName("virtualmachine") IsNot Nothing Then
Dim elem As XmlNodeList = doc.GetElementsByTagName("virtualmachine").Item(0).ChildNodes
For Each item As XmlNode In elem
If item.Name.Equals("state") Then
new_vm_state += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("hostname") Then
new_vm_hostname += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("templatename") Then
new_vm_templatename += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpunumber") Then
new_vm_cpunumber += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpuspeed") Then
new_vm_cpuspeed += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("memory") Then
new_vm_memory += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("nic") Then
new_vm_netmask += ((item.ChildNodes.Item(3).InnerText.ToString()) + Environment.NewLine)
new_vm_gateway += ((item.ChildNodes.Item(4).InnerText.ToString()) + Environment.NewLine)
new_vm_ipaddress += ((item.ChildNodes.Item(5).InnerText.ToString()) + Environment.NewLine)
new_vm_macaddress += ((item.ChildNodes.Item(11).InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("instancename") Then
new_vm_instancename1 += ((item.InnerText.ToString()) + Environment.NewLine)
End If
Console.WriteLine("Finished XML parse")
Next
End If
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-2' - Error parsing returned XML string")
End Try
new_vm_macaddress = new_vm_macaddress.ToUpper
Console.WriteLine("Replacing chars from int IP")
Dim privateip As String = new_vm_ipaddress.Replace(" ", "").ToString
Dim publicip As String = privateip.Replace("172.16.11.", "196.15.17.")
Console.WriteLine("IP formatted correctly")
Try
Console.WriteLine("Entering SQL Try...")
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "DELETE FROM dbcpman_jobs WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("removed job from dbcpman_jobs")
SQL = "UPDATE dbcpman_vm SET deployresponse = '" & jobcheckresult & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated deployresponse in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET macaddress = '" & new_vm_macaddress & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("Updated macaddress in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET publicip = '" & publicip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated publicIP in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET privateip = '" & privateip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated privateIP in dbcpman_vm")
cn.Close()
Console.WriteLine("DB connection closed")
Dim new_vm_username As String = "clouduser"
Dim new_vm_password As String = GeneratePassword(7)
Console.WriteLine("clouduser password generated")
new_vm_password = new_vm_password & "oX7" ''''will remove this once generator can ensure complex passwords
System.Threading.Thread.Sleep(1000)
Dim new_vm_support_username As String = "dbxsupport"
Dim new_vm_support_password As String = GenerateSupportPassword(7)
Console.WriteLine("dbxsupport password generated")
new_vm_support_password = new_vm_support_password & "Kw3" ''''will remove this once generator can ensure complex passwords
cn.Open()
Console.WriteLine("Database connection opened")
myAdapter.SelectCommand = myCommand
SQL = "INSERT into dbcpman_credentials(username1, username2, password1, password2, type, link) VALUES ('" & new_vm_username & "','" & new_vm_support_username & "','" & new_vm_password & "','" & new_vm_support_password & "','Server root logon','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("Saved credentials to dbcpman_credentials")
SQL = "INSERT into dbcpman_vm_boot(dbxid, ip, macaddress, hostname) VALUES ('" & job_dbxid & "','" & new_vm_ipaddress & "','" & new_vm_macaddress & "','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("added VM tags to dbcpman_vm_boot")
cn.Close()
Console.WriteLine("Closed SQL connection")
Try ''''add monitoring for this host
Console.WriteLine("3 - Adding monitoring for " & job_dbxid)
Dim monitorurl As String = "http://192.168.16.32/addhost.php?hostname=" & job_dbxid & "&ipaddr=" & publicip
Dim webClient As New System.Net.WebClient
Dim monresult As String = webClient.DownloadString(monitorurl)
Console.WriteLine("Request sent to add monitoring")
If monresult = "SUCCESS" Then
Console.WriteLine("Monitoring added")
Else
Console.WriteLine("Unable to add monitoring")
End If
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-3' - Error adding monitoring")
End Try
buildcompletedlist.Items.Add(buildpendinglist.Items(i))
Console.WriteLine("Item removed from pending list")
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Console.WriteLine("Item added to complete list")
Catch ex As Exception
MessageBox.Show("ERROR- C " & ccnl & ccnl & ex.Message)
End Try
ElseIf jobcheckresult.Contains("<jobstatus>0</jobstatus>") Then ''If true, job is still pending
Console.WriteLine("Checking on pending job " & buildpendinglist.Items(i) & "...")
ElseIf jobcheckresult.Contains("<jobstatus>2</jobstatus>") Then ''If true, job has failed
Try
Console.WriteLine("An item has failed")
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_jobs SET failed = 'true' WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated Failed in dbcpman_jobs")
cn.Close()
buildfailedlist.Items.Add(buildpendinglist.Items(i))
Console.WriteLine("Item remove from pending list")
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Console.WriteLine("Item added to failed list")
Try
Console.WriteLine("Trying to send email notifying support of a failure...")
Dim Errorbody As String = "Hi, " & ccnl & ccnl & "CloudCommander encountered a problem whilst deploying a VM and attention is required." & _
ccnl & ""
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential(internal_mail_server_username, internal_mail_server_password)
SmtpServer.Port = 25
SmtpServer.Host = internal_mail_server
mail = New MailMessage()
mail.From = New MailAddress("autoattendant#cloud.net")
mail.To.Add("support#cloud.net")
mail.Subject = "[CLOUDFAIL] A cloud server has failed to deploy"
mail.Body = Errorbody
SmtpServer.Send(mail)
Console.WriteLine("Mail sent.")
Catch ex As Exception
Console.WriteLine("Mail failed to send.")
End Try
Catch ex As Exception
End Try
End If
End If
Console.WriteLine("HEADING FOR THE NEXT ITEM")
Console.WriteLine("###################################################")
Next
buildprogresscheckactive = 0
Console.WriteLine("Done with async jobcheck for this pass")
End Sub
Private Sub JobWorker_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles JobWorker.DoWork
End Sub
Private Sub buildpendinglist_SelectedIndexChanged(sender As Object, e As EventArgs) Handles buildpendinglist.DoubleClick
ItemDetails.Show()
End Sub
The thread ... has exited with code 259 (0x103)
This is a known bug in VS2013, the feedback report is here. It doesn't mean anything and the bug is benign, it doesn't affect the way your BackgroundWorker executes. The bug is fixed, it is going to make it to your machine some day. Don't know when.

How Insert datetime from datagridview to database? VB.NET

i want Insert datetime from datagridview to database.But i'm don't save required.
Ex.
Datagridview
DAte
2012-11-20 16:36:39
when i'm save to datagridview to datebase
DAte
1900-01-01 00:00:00.000
I want save 2012-11-20 16:36:39 to dataasbe but it's don't result.
Show Datagridview
Dim sqlSentMaterial As String = ""
Dim DT_SentMaterial As New DataTable
sqlSentMaterial = "SELECT rc.No,rc.ReceiveDate as RCReceiveDate,rc.CreateBy as RCReceiveBy,rc.CreateDate,rc.ReceiveNote "
sqlSentMaterial &= "FROM RClother rc "
sqlSentMaterial &= "Where rc.No ='" & Search & "'"
DT_SentMaterial = FShowData(sqlSentMaterial)
For i As Integer = 0 To DT_SentMaterial.Rows.Count - 1
If DT_SentMaterial.Rows.Count <> 0 Then
Dim item As New DataGridViewRow
item.CreateCells(DgvSentMaterial)
With item
.Cells(1).Value = TxtBarcode.Text
If DT_SentMaterial.Rows(0).Item("RCReceiveDate") Is DBNull.Value Then
.Cells(2).Value = ""
Else
.Cells(2).Value = CDate(DT_SentMaterial.Rows(0).Item("RCReceiveDate")).ToString("dd/MM/yyyy")
End If
End With
DgvSentMaterial.Rows.Add(item)
Exit For
End If
Next
Form save datagridview to database
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Dim sentMat As Integer
sentMat = FInsertSentMatClother(CInt(DgvSentMaterial.Rows(i).Cells(1).Value), CDate(DgvSentMaterial.Rows(i).Cells(2).Value))
End Sub
Function Insert To Database
Public Function FInsert_iPOSentMatClother(ByVal BarCode As Integer, ByVal RCReceiveDate As Date)
Dim Tr As SqlTransaction
Dim sqlCom As New SqlCommand
Dim sqlInsert As String
Dim ReturnValue As Integer
Dim GetDate As DateTime = DateTime.Now
Try
Tr = Conn.BeginTransaction
sqlCom.Connection = Conn
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate & "')"
sqlCom.Transaction = Tr
sqlCom.CommandText = sqlInsert
sqlCom.CommandType = CommandType.Text
ReturnValue = CInt(sqlCom.ExecuteScalar) 'CInt(sqlCom.ExecuteScalar)
If ReturnValue = 0 Then
Tr.Commit()
Else
Tr.Rollback()
End If
Catch ex As Exception
'MsgBox(ex.ToString)
Finally
If Not sqlCom Is Nothing Then
sqlCom.Dispose()
End If
sqlCom = Nothing
End Try
Return ReturnValue
End Function
Thanks you for you time. :)
in your Function insert to database just format Date value in string as you want
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate.ToString("yyyy-MM-dd HH:mm:ss") & "')"
or and on my opinion is a better practice using a parameters:
sqlInsert = "INSERT INTO SentMatClother (BarCode,ReceiveDate) VALUES (#barCode, #receiveDate)"
//then add parameters to your sqlCommand
sqlCom.Parameters.AddWithValue("#barCode", BarCode)
sqlCom.Parameters.AddWithValue("#barCode", RCReceiveDate)

Object reference not set to an instance of an object. For Loop

Function FindUserByCriteria(ByVal _state As String, ByVal _county As String, ByVal _status As String, ByVal _client As String, ByVal _department As String, ByVal _ordernumber As String) As DataTable
'Code to load user criteria from database
Dim ordertype As String
If _status = "Online" Then
ordertype = "Online"
ElseIf _status = "Tax Cert Call" Then
ordertype = "Call"
End If
Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
Dim dbConnection As OleDbConnection = New OleDbConnection(TaxConnStr)
Try
Dim queryString As String
queryString = "Select Username, Amount, Rank FROM UserCriteria "
queryString += "WHERE UserCriteria.State = '" & _state & "' AND UserCriteria.County = '" & _county & "' AND UserCriteria.Status = '" & _status & "' AND UserCriteria.Client = '" & _client & "' AND UserCriteria.Department = '" & _department & "' AND UserCriteria.OrderNumber = '" & _ordernumber & "';"
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
If dataSet.Tables(0).Rows.Count >= 1 Then
FindUserByCriteria = dataSet.Tables(0)
End If
Console.WriteLine(vbCrLf)
For i = 0 To FindUserByCriteria.Rows.Count - 1
If Not IsUserOnline(FindUserByCriteria.Rows(i).Item("UserName")) Then
FindUserByCriteria.Rows(i).Delete()
End If
Next
FindUserByCriteria.AcceptChanges()
Catch ex As Exception
Console.WriteLine(ex.Message)
myLogger.Log(ex.Message)
SendMail(ex.Message)
Finally
dbConnection.Close()
End Try
End Function
So, i get the "Object reference not set to an instance of an object." error at the
For i = 0 To FindUserByCriteria.Rows.Count - 1
line. I swear this was working for me not just 3 days ago...not sure what has changed in my code recently to make this error pop up. Any help would be nice.
you need to reverse the for loop for
For i = FindUserByCriteria.Rows.Count - 1 to 0 step -1
you need to delete backward otherwise you will reach an index already deleted
or you simply need to put the use of any FindUserByCriteria inside the if where it get set
If dataSet.Tables(0).Rows.Count >= 1 Then
FindUserByCriteria = dataSet.Tables(0)
Console.WriteLine(vbCrLf)
For i = 0 To FindUserByCriteria.Rows.Count - 1
If Not IsUserOnline(FindUserByCriteria.Rows(i).Item("UserName")) Then
FindUserByCriteria.Rows(i).Delete()
End If
Next
FindUserByCriteria.AcceptChanges()
End If

Using dbms_output.get_line in VB.NET

I have some stored procedures to execute that use dbms_output.put_line() to put data into the output buffer.
I know I need to use dbms_output.get_line(:line, :status) to retrieve that output.
I'm using System.Data.OracleClient to avoid headaches with Oracle deployment.
So what am I doing wrong with the code below?
Dim cmdSproc As OracleCommand = cnOracle.CreateCommand()
Dim strOracle As New OracleString()
Dim opaLine As New OracleParameter("lineOut", OracleType.VarChar, 255)
opaLine.Direction = ParameterDirection.Output
Dim opaStatus As New OracleParameter("status", 0)
cmdSproc.CommandText = "begin dbms_output.get_line(:lineOut,:status); end;"
cmdSproc.Parameters.Add(opaLine)
cmdSproc.Parameters.Add(opaStatus)
Dim strOutput As String = ""
strOracle = "0"
Try
While strOracle = "0"
cmdSproc.ExecuteOracleNonQuery(strOracle)
strOutput = strOutput & strOracle.ToString() & vbNewLine
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
In vb.net the code format SKINDER friend is as follows... thnxs for sharing
Sub _showDbms()
Dim c As New OracleCommand()
c.Connection = frmMain._cnn
With c
.CommandType = CommandType.Text
.CommandText = "begin dbms_output.get_line(:line, :status); end;"
.Parameters.Add(New OracleParameter("line", OracleDbType.Varchar2)).Size = 32000
.Parameters("line").Direction = ParameterDirection.Output
.Parameters.Add(New OracleParameter("status", OracleDbType.Int32))
.Parameters("status").Direction = ParameterDirection.Output
End With
c.ExecuteNonQuery()
If c.Parameters("line").Value IsNot DBNull.Value Then
MsgBox(c.Parameters("line").Value.ToString)
End If
End Sub
Here's how I got it to work: (found it here)
Dim cmdGetOutput As New OracleCommand("declare " & _
" l_line varchar2(255); " & _
" l_done number; " & _
" l_buffer long; " & _
"begin " & _
" loop " & _
" exit when length(l_buffer)+255 > :maxbytes OR l_done =1; " & _
" dbms_output.get_line( l_line, l_done ); " & _
" l_buffer := l_buffer || l_line || chr(10); " & _
" end loop; " & _
" :done := l_done; " & _
" :buffer := l_buffer; " & _
"end;", cnOracle)
cmdGetOutput.Parameters.Add("maxbytes", OracleType.Int16)
cmdGetOutput.Parameters("maxbytes").Value = 32000
cmdGetOutput.Parameters.Add("done", OracleType.Int16)
cmdGetOutput.Parameters("done").Direction = ParameterDirection.Output
cmdGetOutput.Parameters.Add("buffer", OracleType.LongVarChar, 32000)
cmdGetOutput.Parameters("buffer").Direction = ParameterDirection.Output
Dim strOutput As String = ""
Dim intStatus As Integer = 0
Try
While True
cmdGetOutput.ExecuteNonQuery()
strOutput = strOutput & cmdGetOutput.Parameters("buffer").Value & vbNewLine
If cmdGetOutput.Parameters("done").Value = 1 Then
Exit While
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
MsgBox(strOutput)
cnOracle.Close()
End Try
In C# I am using the next method:
private string GetDbmsOutputLine()
{
OracleCommand command = new OracleCommand
{
Connection = <connection>,
CommandText = "begin dbms_output.get_line(:line, :status); end;",
CommandType = CommandType.Text
};
OracleParameter lineParameter = new OracleParameter("line",
OracleType.VarChar);
lineParameter.Size = 32000;
lineParameter.Direction = ParameterDirection.Output;
command.Parameters.Add(lineParameter);
OracleParameter statusParameter = new OracleParameter("status",
OracleType.Int32);
statusParameter.Direction = ParameterDirection.Output;
command.Parameters.Add(statusParameter);
command.ExecuteNonQuery();
if (command.Parameters["line"].Value is DBNull)
return null;
string line = command.Parameters["line"].Value as string;
return line;
}