How Insert datetime from datagridview to database? VB.NET - 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)

Related

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

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

how to convert a string value into integer in vb.net

Datatype of expense is int in Sql Server database Please Guide
The Value of Expense which i got from the table expense
'Total Expenses B/W Dates
sql = "select COALESCE (SUM (amount), 0) from tblexpense Where transactiondate >= #p1 and transactiondate <= #p2"
CmdObj = New SqlCommand(sql, ConObj)
CmdObj.Parameters.Add("#p1", SqlDbType.Date).Value = DateTimePicker1.Value.Date
CmdObj.Parameters.Add("#p2", SqlDbType.Date).Value = DateTimePicker2.Value.Date
CmdObj.ExecuteScalar()
Dim sumexpense As Integer = CmdObj.ExecuteScalar
LblExp.Text = "Rs. " & sumexpense
Save Button to save The value of expense into table
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
ConObj = New SqlConnection(ConStr)
ConObj.Open()
Dim sql As String = "insert into tblbalance (tcon,pcon,ecoll,pendcoll,expense,bcoll,nprofit) values(#tcon,#pcon,#ecoll,#pendcoll,#expense,#bcoll,#nprofit)"
With CmdObj
.Parameters.Add("#tcon", SqlDbType.Int).Value = lblTcon.Text
.Parameters.Add("#pcon", SqlDbType.Int).Value = LblPcon.Text
.Parameters.Add("#ecoll", SqlDbType.Int).Value = LblEColl.Text
.Parameters.Add("#pendcoll", SqlDbType.Int).Value = LblPColl.Text
.Parameters.Add("#expense", SqlDbType.Int).Value = LblExp.Text
.Parameters.Add("#bcoll", SqlDbType.Int).Value = LblBcoll.Text
.Parameters.Add("#nprofit", SqlDbType.Int).Value = LblNet.Text
End With
CmdObj.Connection = ConObj
CmdObj.ExecuteNonQuery()
MsgBox("Saved Successfully")
ConObj.Close()
End Sub
Imports System.Text.RegularExpressions
Private Shared Function GetIntOnly(ByVal value As String) As Integer
Dim returnVal As String = String.Empty
Dim collection As MatchCollection = Regex.Matches(value, "\d+")
For Each m As Match In collection
returnVal += m.ToString()
Next
Return Convert.ToInt32(returnVal)
End Function
Dim sql As String = "insert into tblbalance (tcon,pcon,ecoll,pendcoll,expense,bcoll,nprofit) values('" &
lblTcon.Text & "','" & LblPcon.Text & "','" & GetIntOnly(LblEColl.Text) & "','" & GetIntOnly(LblPColl.Text) & "','" &
GetIntOnly(LblExp.Text) & "','" & GetIntOnly(LblBcoll.Text) & "','" & GetIntOnly(LblNet.Text) & "')"

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.

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

vb.net check if function don't return anything

I have a vb.net function is which I am doing some thing which is returning a gridview to send it in email.Problem is that when I call the function in email then email is sent even there is nothing returned by function. I don't to send blank email at all. I want to when function return nothing then it shouldn't send email. Here is My function
Public Function emaildata(ByVal grdv As GridView, ByVal chk As String, ByVal celpos As Integer) As GridView
Dim comm As OleDbCommand = New OleDbCommand()
Dim bpv As String = ""
Dim gv As New GridView
For Each gvrow As GridViewRow In grdv.Rows
Try
Dim rdobtn As RadioButtonList = CType(gvrow.FindControl(chk), RadioButtonList)
If rdobtn.SelectedValue.Equals("5") Or rdobtn.SelectedValue.Equals("1") Or rdobtn.SelectedValue.Equals("6") Or rdobtn.SelectedValue.Equals("4") Or rdobtn.SelectedValue.Equals("2") Then
If bpv <> "" Then
bpv += ","
End If
bpv += gvrow.Cells(celpos).Text
comm.CommandText = "SELECT row_number() over(order by rownum) Sr, to_char(chq_num) Cheque#,to_char(bpv_amt,'9,999,999,999') Amount,vch_nar Narration,bnf_nam PartyName,acc_des Bank from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "') union all SELECT null,'Total :',to_char(sum(bpv_amt),'9,999,999,999') Amount,null,null,null from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "')"
comm.CommandType = CommandType.Text
comm.Connection = con
Dim da As New OleDbDataAdapter(comm)
Dim ds As New DataSet
da.Fill(ds)
gv.DataSource = ds
gv.DataBind()
End If
Catch ex As Exception
Response.Write("There is Problem In Cheque Approval System Please Contact With IT")
End Try
Next
Return gv
End Function
And I Call this in email function as a subject like this
email("malik.adeel#shakarganj.com.pk", "[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4), gridhtm(emaildata(GridView5, "chkStatusGM", 4)))
How can I do this that if emaildata(GridView5, "chkStatusGM", 4) returning nothing email shouldn't be sent?
Probably the easiest is to check if the GridView contains GridViewRows with the Count property:
Dim grdEmail = emaildata(GridView5, "chkStatusGM", 4)
If grdEmail.Rows.Count > 0
email("malik.adeel#shakarganj.com.pk",
"[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4),
gridhtm(grdEmail))
End If