Can't solve this Query on checkbox - VB.net MYSQL Query - vb.net

When check the science checkbox . The Science will show in a DataGridView but when i check the Reading and Science, the two subject is can't show on the DataGridView. What is the best way(code) to solve this problem. Thanks in advance.
`Public com As New MySql.Data.MySqlClient.MySqlCommand
Public da As New MySql.Data.MySqlClient.MySqlDataAdapter
Public dr As MySql.Data.MySqlClient.MySqlDataReader
Public dt As New DataTable
Public dt2 As New DataTable
Public ds As DataSet
Dim strSQL As String
Dim strSQL2 As String
Private Sub gbsubject_Enter(sender As Object, e As EventArgs) Handles gbsubject.Enter
Dim SDA As New MySql.Data.MySqlClient.MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
If cbxscience.Checked = True Then
con.Close()
con.Open()
strSQL2 = "SELECT subject_tbl.subject, lessonplan_tbl.lessontitle, kind_tbl.kind FROM kind_tbl INNER JOIN(lessonplan_tbl INNER JOIN(subject_tbl INNER JOIN skul_tbl ON subject_tbl.subjectID = skul_tbl.subjectID) ON lessonplan_tbl.lessonplanID = skul_tbl.lessonplanID) ON kind_tbl.kindID = skul_tbl.kindID WHERE subject_tbl.subject = '" & "SCIENCE" & "'"
dgvlessonplan.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.None
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL2, con)
SDA.SelectCommand = com
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
dgvlessonplan.DataSource = bSource
SDA.Update(dbDataSet)
con.Close()
End If
If cbxreading.Checked And cbxscience.Checked Then
con.Close()
con.Open()
strSQL2 = "SELECT subject_tbl.subject, lessonplan_tbl.lessontitle, kind_tbl.kind FROM kind_tbl INNER JOIN(lessonplan_tbl INNER JOIN(subject_tbl INNER JOIN skul_tbl ON subject_tbl.subjectID = skul_tbl.subjectID) ON lessonplan_tbl.lessonplanID = skul_tbl.lessonplanID) ON kind_tbl.kindID = skul_tbl.kindID WHERE subject_tbl.subject = '" & "READING" & "' and subject_tbl.subject = '" & "SCIENCE" & "'"
dgvlessonplan.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.None
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL2, con)
SDA.SelectCommand = com
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
dgvlessonplan.DataSource = bSource
SDA.Update(dbDataSet)
con.Close()
End If`

You need to use an OR not an AND in your strSQL2 variable.
So, change this:
strSQL2 = "SELECT subject_tbl.subject, lessonplan_tbl.lessontitle, kind_tbl.kind FROM kind_tbl INNER JOIN(lessonplan_tbl INNER JOIN(subject_tbl INNER JOIN skul_tbl ON subject_tbl.subjectID = skul_tbl.subjectID) ON lessonplan_tbl.lessonplanID = skul_tbl.lessonplanID) ON kind_tbl.kindID = skul_tbl.kindID WHERE subject_tbl.subject = '" & "READING" & "' and subject_tbl.subject = '" & "SCIENCE" & "'"
to this:
strSQL2 = "SELECT subject_tbl.subject, lessonplan_tbl.lessontitle, kind_tbl.kind FROM kind_tbl INNER JOIN(lessonplan_tbl INNER JOIN(subject_tbl INNER JOIN skul_tbl ON subject_tbl.subjectID = skul_tbl.subjectID) ON lessonplan_tbl.lessonplanID = skul_tbl.lessonplanID) ON kind_tbl.kindID = skul_tbl.kindID WHERE subject_tbl.subject = 'READING' OR subject_tbl.subject = 'SCIENCE'"

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

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

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

EXTRACT query in Vb.net using sql

This is my code then the problem is it will not show the information in the gridlist. I want to make inner join of my two tables but it doesn't work with my codes. What will be the alternative way of this? Thank you so much for answering.
Dim sqlQuery As String = "SELECT Persons.pr_id, Persons.pr_fname, Persons.pr_mname, Persons.pr_lname, Persons.pr_address, Users.UserName, Users.phone_num FROM Persons" & _
"INNER JOIN Users ON Persons.pr_id = Users.pr_id" & _
" WHERE pr_id='" & TextBox1.Text & "'"
Dim table As New DataTable
cn.Close()
cn.Open()
With cmd
.CommandText = sqlQuery
.Connection = cn
End With
With cmd
.CommandText = sqlQueryUser
.Connection = cn
End With
With sqla
.SelectCommand = cmd
.Fill(table)
End With
If ListView1.SelectedItems.Count > 0 Then
'Button20.Visible = True
'Button10.Visible = True
'RichTextBox2.Enabled = False
'senbyCombo.Enabled = False
'group_sendCombo.Enabled = False
'title.Enabled = False
'ListView3.Enabled = True
id = ListView1.SelectedItems(0).Text
TextBox1.Text = ListView1.SelectedItems(0).SubItems(0).Text
TextBox2.Text = ListView1.SelectedItems(0).SubItems(1).Text
TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text
TextBox4.Text = ListView1.SelectedItems(0).SubItems(3).Text
TextBox5.Text = ListView1.SelectedItems(0).SubItems(4).Text
TextBox7.Text = ListView1.SelectedItems(0).SubItems(6).Text
End If
cn.Close()
your pr_id is ambiguous change your query like this :
Dim sqlQuery As String = "SELECT Persons.pr_id, Persons.pr_fname, Persons.pr_mname, Persons.pr_lname, Persons.pr_address, Users.UserName, Users.phone_num FROM Persons" & _
"INNER JOIN Users ON Persons.pr_id = Users.pr_id" & _
" WHERE Persons.pr_id='" & TextBox1.Text & "'"

Load SQL Statement for Dataset From SqlServer

I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.