how to convert a string value into integer in vb.net - 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) & "')"

Related

Multiselection in vb.net ListBox

I have a list of student names in a listBox,(studentList)I click on a name in the box and get all the students details up ie name, course, subject etc.The code then gets the details from the database(in my case it's access) then displays it in a datagridview.
The code works fine if I just select one item from one(or all)List Boxes.My question is, can I select more than one item per LitsBox.I know I can use SelectedMode property to allow the highlighting but that wont draw the required data from the database.Here is the code I am using vb.10
`Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim isFirstColumn As Boolean = True
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim x As String = studentList.Text
Dim y As String = courseList.Text
Dim z As String = gradeList.Text
Dim defaultSQL As String = "SELECT * FROM studentfile "
If studentList.SelectedIndex > -1 Then
If isFirstColumn Then
student = "WHERE student = '" & x & "' "
Else
student = "AND student = '" & x & "' "
End If
isFirstColumn = False
End If
If courseList.SelectedIndex > -1 Then
If isFirstColumn Then
course = "WHERE course = '" & y & "' "
Else
course = "AND course = '" & y & "' "
End If
isFirstColumn = False
End If
If gradeList.SelectedIndex > -1 Then
If isFirstColumn Then
grade = "WHERE grade = '" & z & "' "
Else
grade = "AND grade = '" & z & "' "
End If
isFirstColumn = False
End If
Dim sql As String = defaultSQL & student & course & grade
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub`
many thanks
grey
Using the .SelectedItems (and a lot of jiggery with the where clause.... you should be able to use this to EITHER have multi-select of single select accross all three listboxes as well as not selecting anything from any of them too...
The only question I would have would be whether you want all the 'AND's as this would mean if you selected two students, you wouldnt get any results... as no two students are the same right? Unless you selected two 'Dave's in which it would return both. For example!
Might suggest changing some for 'OR's or look at what the end result might be? Either way comment and let us know if need any further help
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim defaultSQL As String = "SELECT * FROM studentfile "
Dim WhereClause As String = ""
Dim StudentCourseGrade As String
'Students---------------------------------------------
For Each stu In studentList.SelectedItems
StudentCourseGrade = "(student='" & stu & "'"
For Each crs In courselist.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND course = '" & crs & "'"
For Each grd In gradeList.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND grade = '" & crs & "'"
Next
Next
StudentCourseGrade = StudentCourseGrade & ")"
If WhereClause.Length = 0 Then
WhereClause = "WHERE " & StudentCourseGrade
Else
WhereClause = " OR " & StudentCourseGrade
End If
Next
'Students---------------------------------------------
Dim SQL As String = defaultSQL & WhereClause
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub
Hth
Chicken

VB.NET: Cannot display selected data from access database into datagridview

I have been trying to display selected data from Access database into datagridview on pressing the button but its not displaying any records neither it is showing any error.
Dim third_da As OleDb.OleDbDataAdapter
Dim third_ds As New DataSet
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con.Open()
Dim cb_two As New OleDb.OleDbCommandBuilder(third_da)
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " & _
"FROM emp_timing WHERE (((emp_timing.emp_code)=" & empcode & ") AND ((emp_timing.day) Like '??/" & ComboBox1.Text & "/20" & TextBox9.Text & "'))"
' "WHERE (((emp_timing.emp_code)=22) AND ((emp_timing.day) Like '??/05/2016'))"
third_da = New OleDb.OleDbDataAdapter(query_three, con)
third_da.Fill(third_ds, "ets")
DataGridView1.DataSource = third_ds.Tables("ets")
con.Close()
Dim view As New DataView(third_ds.Tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
DataGridView1.ReadOnly = True
DataGridView1.CancelEdit()
End Sub
Thanks in Advance!
You can change you condition of emp_timing.day field in query like this :
(Month(emp_timing.day) = & ComboBox1.Text &
and Year(emp_timing.day) = "20" & TextBox9.Text & " )
But, I advice you to use the Parameter to avoid SQL injections , like this :
query_three = "SELECT emp_timing.emp_code, emp_timing.day, emp_timing.travel_time, emp_timing.travel_dest,emp_timing.emp_timein,emp_timing.emp_timeout, emp_timing.emp_hours, emp_timing.emp_mins " &
"FROM emp_timing WHERE (((emp_timing.emp_code)= #empcode) AND ((emp_timing.day) BETWEEN #startDate AND #endDate ))"
Dim startDate As New DateTime("20" & TextBox9.Text, ComboBox1.Text, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
Dim cmd As New OleDbCommand(query_three, con)
cmd.Parameters.AddWithValue("#empcode", empcode)
cmd.Parameters.AddWithValue("#startDate", startDate.ToString("#yyyy/MM/dd#"))
cmd.Parameters.AddWithValue("#endDate", endDate.ToString("#yyyy/MM/dd#"))
third_da = New OleDb.OleDbDataAdapter(cmd)

Converting a OleDbDataReader to a String to display a COUNT command in List View

I want to display in a ListView the COUNT of a specific Employee Name whilst using two MS Access queries. The COUNT that is being displayed is only 0, 1 or 2 but there are many none "----" values in the database.
The command is binded to a RadioButton:
Private Sub RadioButton2_Click(sender As Object, e As EventArgs) Handles RadioButton2.Click
Dim con As New OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\sheetlog.mdb;Jet OLEDB:Database Password = 'password';")
con.Open()
Dim try2 As String = "----"
Dim try3 As String
Dim oledbCmd, oledbCmd2 As OleDbCommand
Dim cmd, cmd2 As String
cmd = "SELECT DISTINCT empname FROM sheet"
oledbCmd = New OleDbCommand(cmd, con)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
ListView1.Clear()
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.View = View.Details
ListView1.MultiSelect = False
ListView1.Columns.Add("Employee Name", 130)
ListView1.Columns.Add("New", 80)
ListView1.Columns.Add("Rev1", 80)
ListView1.Columns.Add("Rev2", 80)
ListView1.Columns.Add("Rev3", 80)
ListView1.Columns.Add("Rev4", 80)
ListView1.Columns.Add("Rev5", 80)
While (oledbReader.Read)
try3 = oledbReader("empname").ToString
cmd2 = "SELECT count(new) AS cnew, count(rev1) AS crev1, count(rev2) AS crev2, count(rev3) AS crev3, count(rev4) AS crev4, count(rev5) AS crev5 FROM sheet WHERE empname = '" & try3 & "' AND rev1 <> '" & try2 & "' AND rev2 <> '" & try2 & "' AND rev3 <> '" & try2 & "' AND rev4 <> '" & try2 & "' AND rev5 <> '" & try2 & "'"
oledbCmd2 = New OleDbCommand(cmd2, con)
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While
End While
con.Close()
End Sub
I've been away from VB.NET for a bit, but I think you need to do While(oledbReader2.Read())for the second DataReader:
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
' I think you need this here:
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While

How to add multiple prdoucts including their id, qty and price as a single transaction to a Access database?

I have a shopping cart page which lists 12 books with 12 buttons assigned each to a book item, the user is able to click each button and add the price and qty to a Session in VB. So if a customer wants to order all 12 books they would click all twelve buttons and the price and qty of each product would be added to a Session. My problem is when the customer completes the form validation how do I assign all 12 items with their sessions to a MS Access database in a single transaction using session.id?
Protected Sub order_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If (Page.IsValid) Then
Dim strSessionID As String
strSessionID = Session.SessionID
Dim strFullname As String
Dim strAddress As String
Dim strPostcode As String
Dim intCardNo As Long
Dim strCardType As String
Dim dateOfOrder As Date
dateOfOrder = Session("dateOfOrder")
Dim dblTotalCost As String
dblTotalCost = Session("dblTotalCost")
Dim intProduct001 As String
intProduct001 = Session("product001")
Dim intProduct002 As Integer
intProduct002 = Session("product002")
Dim intProduct003 As Integer
intProduct003 = Session("product003")
Dim intProduct004 As Integer
intProduct004 = Session("product004")
Dim intProduct005 As Integer
intProduct005 = Session("product005")
Dim intProduct006 As Integer
intProduct006 = Session("product006")
Dim intProduct007 As Integer
intProduct007 = Session("product007")
Dim intProduct008 As Integer
intProduct008 = Session("product008")
Dim intProduct009 As Integer
intProduct009 = Session("product009")
Dim intProduct010 As Integer
intProduct010 = Session("product010")
Dim intProduct011 As Integer
intProduct011 = Session("product011")
Dim intProduct012 As Integer
intProduct012 = Session("product012")
strFullname = fullname.Text
Session("fullname") = strFullname
strAddress = address.Text
Session("address") = strAddress
strPostcode = postcode.Text
Session("postcode") = strPostcode
intCardNo = cardN0.Text
Session("CardN0") = intCardNo
strCardType = cardType.Text
Session("CardType") = strCardType
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("ecommerceDatabase.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Orders(SessionID, orderDate, orderTotal ) " & _
"Values ('" & strSessionID & "','" & dateOfOrder & "','" & dblTotalCost & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
Dim strDatabaseNameAndLocation2 As String
strDatabaseNameAndLocation2 = Server.MapPath("ecommerceDatabase.mdb")
Dim strSQLCommand2 As String
strSQLCommand2 = "INSERT INTO Customers(SessionID, Fullname, Address, Postcode, CardNo, CardType) " & _
"Values ('" & strSessionID & "', '" & strFullname & "', '" & strAddress & "', '" & strPostcode & "', '" & intCardNo & "', '" & strCardType & "');"
Dim objOleDbConnection2 As System.Data.OleDb.OleDbConnection
objOleDbConnection2 = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation2)
objOleDbConnection2.Open()
Dim objOleDbCommand2 As System.Data.OleDb.OleDbCommand
objOleDbCommand2 = New System.Data.OleDb.OleDbCommand(strSQLCommand2, objOleDbConnection2)
objOleDbCommand2.ExecuteNonQuery()
objOleDbConnection2.Close()
Response.Redirect("validate.aspx")
End If
You will need to run all of your SQL commands using a single connection, and call OleDbConnection.BeginTransaction on the connection, and OleDbTransaction.Commit on the returned transaction object. You should put your product IDs into a List(Of String) to minimize the code, and you should parameterize your queries to avoid SQL injections issues.
The following pseudocode illustrates the general idea:
Dim productIDs = New List(Of String)()
productIDs.Add(Session("product001")) ' Should be in a loop!
' etc.
Using cn = New OleDbConnection(...)
cn.Open()
Using tran = cn.BeginTransaction(IsolationLevel.Serializable) ' or other isolation level
Using cmd = new OleDbCommand(sql1, cn, tran) ' Customers
' Set command parameters
cmd.ExecuteNonQuery()
End Using
Using cmd = new OleDbCommand(sql2, cn, tran) ' Orders
' Set command parameters
cmd.ExecuteNonQuery()
End Using
For Each productID In productIDs
Using cmd = new OleDbCommand(sql3, cn, tran) ' OrderProducts?
' Set command parameters
cmd.ExecuteNonQuery()
End Using
Next
tran.Commit()
End Using
End Using

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)