Multiselection in vb.net ListBox - sql

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

Related

Access Database VB - Searching a database for most 'RECENT' record

I was wondering how I could change the code below, to allow me to search for the most recent record. I am creating a Hotel Booking System and want to use the most recent price in the database but at the moment, it is just searching using the labels which I don't want.
Dim str1 As String
Dim dbpassword As String = "123"
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= E:\Computing\Hotel Booking System\Database\Hotel Booking System.accdb ;Jet OLEDB:Database Password =" & dbpassword & ";"
Dim MyConn As OleDbConnection
Dim dr As OleDbDataReader
Private Sub Information_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim PriceFound As String = False
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
str1 = ("SELECT * FROM [Prices] WHERE [Adult] = '" & LblPriceAdult.Text & "' AND [Child] = '" & LblPriceChild.Text & "'")
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
dr = cmd1.ExecuteReader
While dr.Read()
PriceFound = True
DateDisplay = dr("ID").ToString
AdultPrice = dr("Adult").ToString
ChildPrice = dr("Child").ToString
SingleRoom = dr("Single").ToString
DoubleRoom = dr("Double").ToString
FamilyRoom = dr("Family").ToString
If PriceFound = True Then
LblPriceAdult.Text = AdultPrice
LblPriceChild.Text = ChildPrice
LblPriceDoubleRoom.Text = DoubleRoom
LblPriceFamilyRoom.Text = FamilyRoom
LblPriceSingleRoom.Text = SingleRoom
End If
End While
MyConn.Close()
End Sub
Based on your previous comments, you need to rewrite your SQL to trap the most recent record.
Try something like this:
SELECT MAX(ID) FROM [Prices] ORDER BY ID DESC
I tried the answer above. However for the code above, it wouldn't search for the most recent so I changed DESC to ASC

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

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

Input array is longer than the number of columns

In the event dragdrop of a datagridview I got this error:
Here's the whole code of my dragdrop event :
Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(clientPoint.X, clientPoint.Y)
Dim dgvr As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim celldata As Object() = New Object(dgvr.Cells.Count) {}
For col As Integer = 0 To dgvr.Cells.Count - 1
celldata(col) = dgvr.Cells(col).Value
Next
Dim dt As New DataTable()
dt = ds_data.Tables(0)
Dim colCheckbox As DataColumn = dt.Columns.Add("Column1", GetType(Boolean))
Dim row As DataRow = dt.NewRow()
row.ItemArray = celldata
dt.Rows.InsertAt(row, hit.RowIndex)
dgvr.DataGridView.Rows.Remove(dgvr)
Dim sqlCmd As SqlCommand
sqlCmd = con.CreateCommand()
sqlCmd.CommandText = "update megatom_data_commande set ordre='" & hit.RowIndex & "' where id='" & DataGridView1.Rows(hit.RowIndex).Cells("ID").Value.ToString & "'"
Try
sqlCmd.ExecuteNonQuery()
DataGridView2.DataSource = ds_data2.Tables(0).DefaultView
DataGridView1.DataSource = ds_data.Tables(0).DefaultView
Dim CMD As New SqlCommand("PLANNIFIER")
CMD.Parameters.Add("#CHAINE", SqlDbType.VarChar).Value = cboChaine.SelectedItem.ToString
ExecuteCMD(CMD)
Catch ex As SqlException
End Try
End Sub
In fact my datatable have 15 columns but I added manually a checkbox column to select rows so I think i have a problem of indexes but I dont know how to resolve that problem.
My ds_data is defined like the code below:
requestPlanifie = "select megatom_data_commande.id as ID,numéro,observation,moule,commande,id_etat,programme,ordre,moule,glav,Qté_commandée_Totale," _
& " Qté_coupée_cuir, Qté_coupée_synthétique, Qté_piquée, Qté_finie from megatom_data_commande" _
& " inner join dbo.MEGATOM_DATA_MOULE on megatom_data_moule.id=megatom_data_commande.id_moule " _
& " where id_chaine='" & cboChaine.Text & "' and ( id_etat='3' or id_etat='4') order by numéro asc,ordre asc"
Dim dataAdapter As New SqlDataAdapter(requestPlanifie, con)
Try
dataAdapter.Fill(ds_data, "ds_data")
dataAdapter2.Fill(ds_data2, "ds_data2")
Catch ex As SqlException
End Try
DataGridView1.DataSource = ds_data.Tables(0).DefaultView

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