Converting a OleDbDataReader to a String to display a COUNT command in List View - vb.net

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

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

How to insert a cell with data into it into datagridview with single column?

I have a child form (form2) that is open and is having a datagridview with single column. I filled it with data using datatable.
Now, on a button click event of parent form (form1) i am opening another form (form3) that accepts some value. I want to insert that value in datagridview in child form (form2). That value is also updating database from where the data comes into datagridview.
IN FORM : 3
Dim comStr As String = "Insert into Clinicinfo values (newid(), '" & clinicnameTxt.Text & "', '" & doctorsnameTxt.Text & "', '(" & doctordegreeTxt.Text & ")', '" & clinicaddresTxt1.Text & "', '" & clinicaddressTxt2.Text & "', '" & contactnoTxt.Text & "', '" & opeaningtimeDTP.Text & "', '" & closingtimeDTP.Text & "', 'Active')"
Main.ClName = clinicnameTxt.Text
Dim comm As New SqlCommand(comStr, conn)
If MessageBox.Show("Are you sure want to save data ?", "Saving Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = vbYes Then
comm.ExecuteNonQuery()
MessageBox.Show("Data saved successfully.")
'SelectClinic.clNameDGV.Rows.Add(New String() {clinicnameTxt.Text})////TRIED
Dim adStr As String = "Select Distinct Clinic_Name from Clinicinfo Where Clinic_Status = 'Active'"
Dim Adcomm As New SqlCommand(adStr, conn)
Dim adrd As SqlDataReader
Dim dt As New DataTable
adrd = comm2.ExecuteReader
dt.Load(adrd)
Dim nf As New SelectClinic
nf.clNameDGV.Columns.Clear()
nf.clNameDGV.AllowUserToAddRows = False
nf.clNameDGV.AutoGenerateColumns = True
nf.clNameDGV.DataSource = dt
rd.Close()
End If
IN FORM 2 :
comStr2 = "Select Distinct Clinic_Name from Clinicinfo Where Clinic_Status = 'Active'"
End If
Dim comm2 As New SqlCommand(comStr2, conn)
Dim rd As SqlDataReader
Dim dt As New DataTable
rd = comm2.ExecuteReader
dt.Load(rd)
'clNameDGV.Columns.Clear()
clNameDGV.AllowUserToAddRows = False
clNameDGV.AutoGenerateColumns = True
clNameDGV.DataSource = dt
clNameDGV.Refresh()
rd.Close()
IN FORM 1 :
Private Sub CreateClinicAccountToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CreateClinicAccountToolStripMenuItem.Click
Dim nf As New ClinicDetails
nf.MdiParent = Me
nf.Show()
End Sub

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) & "')"

Copy the contents(including headers) of a ListView to a DataGridView in VB.net

I have a ListView that has values from a database. I used two MS Access OLEDB Statements to produce the data I have. So I used two While Loops. The second OLEDB Statement is with reference to the first. How do I insert all the contents of my ListView to a DataGridView?
Here is my code for the two While loops that is used to call out the OLEDB Statements:
Dim connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\STSlog.mdb;Jet OLEDB:Database Password=password;"
Dim conn As New OleDbConnection(connectionstring)
Dim command, command2, command3 As New OleDbCommand
Dim commstring, commstring2, commstring3 As String
Dim searchstring As String
commstring = "SELECT DISTINCT empname FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' ORDER BY empname ASC"
command = New OleDbCommand(commstring, conn)
commstring3 = "SELECT SUM([Regular]) AS sRegular, SUM(OT) AS sOT FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command3 = New OleDbCommand(commstring3, conn)
MainLView.Clear()
MainLView.GridLines = True
MainLView.FullRowSelect = True
MainLView.View = View.Details
MainLView.MultiSelect = True
MainLView.Columns.Add("Employee Name", 290)
MainLView.Columns.Add("Total Regular", 200)
MainLView.Columns.Add("Total Overtime", 200)
MainLView.Columns.Add("Total Hours", 200)
conn.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim RegSum, OTSum, Total As Decimal
While reader.Read
searchstring = reader("empname")
commstring2 = "SELECT SUM([Regular]) AS sReg, SUM(OT) AS sOT FROM data WHERE empname = '" & searchstring & "' AND ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command2 = New OleDbCommand(commstring2, conn)
Dim reader2 As OleDbDataReader = command2.ExecuteReader()
While reader2.Read
RegSum = (reader2("sReg"))
OTSum = (reader2("sOT"))
Total = Format((RegSum + OTSum), "0.0")
With MainLView.Items.Add(reader("empname"))
.subitems.add(reader2("sReg"))
.subitems.add(reader2("sOT"))
.subitems.add(Total)
End With
End While
End While
I added columns first to my DataGridView then inserted the data from the database using DataGridView Rows.
Dim connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\STSlog.mdb;Jet OLEDB:Database Password=password;"
Dim conn As New OleDbConnection(connectionstring)
Dim command, command2, command3 As New OleDbCommand
Dim commstring, commstring2, commstring3 As String
Dim searchstring As String
commstring = "SELECT DISTINCT empname FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' ORDER BY empname ASC"
command = New OleDbCommand(commstring, conn)
commstring3 = "SELECT SUM([Regular]) AS sRegular, SUM(OT) AS sOT FROM data WHERE ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command3 = New OleDbCommand(commstring3, conn)
MainLView.Clear()
MainLView.GridLines = True
MainLView.FullRowSelect = True
MainLView.View = View.Details
MainLView.MultiSelect = True
MainLView.Columns.Add("Employee Name", 290)
MainLView.Columns.Add("Total Regular", 200)
MainLView.Columns.Add("Total Overtime", 200)
MainLView.Columns.Add("Total Hours", 200)
Dim col1 As New DataGridViewTextBoxColumn
Dim col2 As New DataGridViewTextBoxColumn
Dim col3 As New DataGridViewTextBoxColumn
Dim col4 As New DataGridViewTextBoxColumn
col1.HeaderText = "Employee Name"
col2.HeaderText = "Total Regular"
col3.HeaderText = "Total Overtime"
col4.HeaderText = "Total Hours"
ReportDGV.Columns.Add(col1)
ReportDGV.Columns.Add(col2)
ReportDGV.Columns.Add(col3)
ReportDGV.Columns.Add(col4)
conn.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim RegSum, OTSum, Total As Decimal
While reader.Read
searchstring = reader("empname")
commstring2 = "SELECT SUM([Regular]) AS sReg, SUM(OT) AS sOT FROM data WHERE empname = '" & searchstring & "' AND ProjectCode = '" & PrjctCmbBox.SelectedItem.ToString & "' "
command2 = New OleDbCommand(commstring2, conn)
Dim reader2 As OleDbDataReader = command2.ExecuteReader()
While reader2.Read
RegSum = (reader2("sReg"))
OTSum = (reader2("sOT"))
Total = Format((RegSum + OTSum), "0.0")
With MainLView.Items.Add(reader("empname"))
.subitems.add(reader2("sReg"))
.subitems.add(reader2("sOT"))
.subitems.add(Total)
Dim row As String() = New String() {reader("empname"), reader2("sReg"), reader2("sOT"), Total}
ReportDGV.Rows.Add(row)
End With
End While
End While

I am getting Error "There is no row at position 0" from code below

Private Sub Button3_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End If
End Sub
The message comes when i enter a wrong or non-existent Employee code in txtID.text
how can i solve tha problem
try as below
you should always check dataset table and rows count
i am not much familiar with vb .net(i am in C#) but i think following is good to go
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
If ds.Tables.Count > 0 AndAlso ds.Tables("IBCARIP").Rows.Count >0 Then
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End if
End If
End Sub
First the most important: you are open for SQL-Injection since you are not using sql-parameters but concatenating the query with user input.
The reason for the error is that you are trying to access the a DataRow in the DataTable without checking if there is at least one. But you are accessing the row with index inc, maybe the table does not contain so many rows. Why do you use a variable at all here?
da.Fill(ds, "IBCARIP")
If ds.Tables("IBCARIP").Rows.Count = 0 Then Return ' or something else
' here you can safely access the first row...
Here the long version with parameters:
Using con = New OleDbConnection(dbProvider & dbSource)
Dim sql = "select * from Calculator where EmpCode=?"
Using da = New OleDbDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#EmpCode", txtID.Text)
da.Fill(ds, "IBCARIP")
If ds.Tables("").Rows.Count > 0 Then
Dim row = ds.Tables("IBCARIP").Rows(0)
Dim SName = row.Field(Of String)("SName")
Dim FName = row.Field(Of String)("FName")
Dim sai = String.Format("{0}{1}", SName, FName)
lblSAI.Text = sai
' ... '
End If
End Using
End Using