how to use multiple combo boxes to filter data - vb.net

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.

you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.

Related

Need to close program to see datagrid changes after making a search query and update the results

I execute the search query and after that i want to update the results but datagridview doesnt update, need to close and reopen to see the results.
Can anyone help? dont know if the problem is in the update button or the search
Update button
Call cn()
Dim teste As String
teste = "UPDATE CARROS SET processo = '" & processo & "', estado = '" & estado & "', tecnico = '" & tecnico & "', data = #" & data & "# , localizacao = '" & localizacao & "', [Pedido/PI] = '" & pedido & "'
WHERE Código = " & codigo
updatee = New OleDb.OleDbCommand(teste, connection)
updatee.ExecuteNonQuery()
MessageBox.Show("Actualizado com sucesso")
connection.Close()
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
SEARCH Button
Dim locali As String
Call cn()
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Else
locali = pesqtxt.Text
'Codigo SQL
sql = "Select *
FROM CARROS
WHERE (processo LIKE '%" & locali & "%') OR
(estado LIKE '%" & locali & "%') OR
(data Like '%" & locali & "%') OR
(localizacao Like '%" & locali & "%') OR
(tecnico Like '%" & locali & "%')"
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds)
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
connection.Close()
As far as the Search code goes, you cannot find out if a String is "Like" as Date.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. Keep you database objects local and open connections as late as possible anc close as soon as possible.
Private Sub UpdateDatabse()
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("UPDATE CARROS SET processo = #processo, estado = #estado, tecnico = #tecnico, data = #data , localizacao = #localizacao, [Pedido/PI] = #pedido WHERE Código = #codigo", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar, 50).Value = processo
.Add("#estado", OleDbType.VarChar, 50).Value = estado
.Add("#tecnico", OleDbType.VarChar, 50).Value = tecnico
.Add("#data", OleDbType.Date).Value = CDate(Data)
.Add("#localizacao", OleDbType.VarChar, 50).Value = localizacao
.Add("#peido", OleDbType.VarChar).Value = pedido
.Add("#codigo", OleDbType.Integer).Value = codigo
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Actualizado com sucesso")
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS) 'No way for me to check this
End Sub
Private Sub Search(locali As String)
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("Select *
FROM CARROS
WHERE (processo LIKE #processo) OR
(estado LIKE #estado) OR
(localizacao Like #localizacao) OR
(tecnico Like #tecnico);", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#estado", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#localizacao", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#tecnico", OleDbType.VarChar).Value = "%" & locali & "%"
End With
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
If dt.Rows.Count > 0 Then
CARROSDataGridView.DataSource = Nothing
CARROSDataGridView.DataSource = dt
Else
MessageBox.Show("No matching records found")
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Return
End If
Search(pesqtxt.Text)
End Sub
Try the Refresh option on the grid after you have loaded the updated data.
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
CARROSDataGridView.Refresh

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

Combining two Columns

I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename.
I have tried this code
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', CONCATE(Textbox2.text, ',', Textbox3.Text))"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
The section CONCATINATE will be like the following:
"CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))"
But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types.
Example:
Dim query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (" & _
"#adm,#fName,#mName,CONCATE(#fNameC,',',#mNameC))"
Dim cmd As New SqlCommand(query, cn)
cmd.Parameters.Add("#adm", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mName", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#fNameC", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mNameC", SqlDbType.VarChar).Value = TextBox3.Text
'Execute the query here
Before query first store two textbox value in one variable
cn.Open()
Dim query As String
Dim fullname As String
fullname = TextBox1.text + "" + TextBox2.text
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & fullname & '")"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
You can concatenate with String.Concat, and I advice you to use the Parameter to avoid sql injections, like this :
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", TextBox2.Text))
cmd.Parameters.Add(New SqlParameter("#MiddleName", TextBox3.Text))
cmd.Parameters.Add(New SqlParameter("#FullName", String.Concat(TextBox2.Text, ",", TextBox3.Text)))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Save the Firstname and Middlename values into variables and concat() them together before sending to the query.
cn.Open()
Dim query As String
Dim firstname As String
Dim middlename As String
Dim fullname As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
firstname = TextBox2.Text
middlename = TextBox3.Text
fullname = String.Concat(firstname, ",", middlename)
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", firstname))
cmd.Parameters.Add(New SqlParameter("#MiddleName",middlename))
cmd.Parameters.Add(New SqlParameter("#FullName", fullname))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Note that the query builder has been reformatted to remove vulnerability to SQL injection.
Use following line instead of your.
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & Textbox2.Text & " " & Textbox3.Text & "')"

syntax error missing operator in query expression "Username = and level like '%instructor%'

this code below"" is working if its in "search button" but I would like to use this in "Load form" that when i run it should automatically display data into datagridview which giving error on the above mentioned. any suggestion would be appreciated.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
If Me.cboSearchBy.Text = "Name" Then
sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like '%" & Me.txtSearch.Text & "%'"
sSQL = sSQL & " and level like '%instructor%'"
Else
sSQL = sSQL & " where Username =" & Me.txtSearch.Text
sSQL = sSQL & " and level like '%instructor%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
When the form starts and there is no text in the txtSearch textbox your query becomes syntactically wrong. If you had used a parameterized query you would have avoided this error.
(Not to mention the famigerate Sql Injection problem)
Using conn = New OleDbConnection(Get_Constring)
Using cmd = new OleDbComman()
conn.Open()
cmd.Connection = conn
sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
If Me.cboSearchBy.Text = "Name" Then
sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like ? and level like ?"
Else
sSQL = sSQL & " where Username = ? and level like ?"
End If
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#1", "%" & txtSearch.Text & "%")
cmd.Parameters.AddWithValue("#2", "%instructor%")
Using da = new OleDbDataAdapter(cmd)
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
End Using
End Using
Also, if you are using an MS-Access database keep in mind that PASSWORD is a reserved keyword and you need to encapsulate it between square brackets when used in query like the one above.
SELECT ......., [Password] ........

Data Reader formatting output

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.
The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf