SQL select statement with 2 conditions - sql

I have a table that has columns CustomerCell and ReceiptType. I need to create a SELECT statement that displays every record that matches CustomerCell or ReceiptType.
I tried this code:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = '" & TextBox1.Text & "') or ([RcptType] = 'Cash') "
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
End If
Where Textbox1 is for CustomerCell and CheckBox4 is for ReceiptType. When I enter customer cell and receipt type I should see 2 records however with the above code I can see only one record.
This is my form:

As stated, look into parameters to avoid SQL injection and it does clear up your query a little more. I've put this together which may help. Might need a few tweaks for your application:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim dt As DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = #RcptCustCell) or ([RcptType] = 'Cash') "
Using con As New SqlConnection(constr),
com As New SqlCommand(sqlstr, con)
com.Parameters.Add("#RcptCustCell", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
dt = New DataTable
dt.Load(com.ExecuteReader)
dgv.DataSource = dt
Call griddraw()
End Using
End If

Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt]"
If TextBox1.Text.trim.length <> 0 then
sqlstr += "where (RcptCustCell = '" & TextBox1.Text & "')"
endif
If chkPaymentCheck.checked then
if sqlstr.contains("where") = false then
sqlstr += "where RcptType = 'Check'"
EndIf
sqlstr += "or RcptType = 'Check'"
endif
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
Try this and you can continue with the if statements to add more checks.

Related

How to Get Values of specific row wise in TextBox of a specific column

Dim Query As String
Query = "Select * from Charges where DOctype='" & Labeldoctype.Text & "'"
Dim cmd As New SqlCommand(Query, con)
con.Open()
Dim dataAdapter As New SqlDataAdapter(Query, con)
dataAdapter.Fill(dt)
dataAdapter.Dispose()
For i As Integer = 0 To (dt.Rows.Count - 1)
rowindex = i
LabelV001.Text = (dt.Rows(0)("Head")).ToString
LabelV002.Text = (dt.Rows(1)("Head")).ToString
Next
con.Close()

fetching data from SQL server and print it out using loop

I'm trying to fetch all the data rows in a sql server to print all the values. Here is the code I already tried but it still does not work. Can someone tell me what is wrong here? I'm quite new to vb.net
For i = 1 To 100
Dim testsection As String = e.Item.DataItem("sectionName")
e.Item.Cells(4).Text = strSection & testsection
Next
i dont quite understand how it fetch the data. i juz work as a fresh grad. but they already assign me this advance task. here is the codes in my DBFunction.
Public Function GetUserList(ByVal strUserLogin As String, ByVal strName As String, _
ByVal intCompanyID As Integer, ByVal tblName As String) As DataSet
Dim oConn As SqlConnection = Nothing
Dim SQLStr As String = ""
Dim SubSQL As String = ""
Dim CMD As SqlCommand = Nothing
Dim DS As New DataSet
Dim DA As New SqlDataAdapter
Try
oConn = New SqlConnection(ConnectionString)
oConn.ConnectionString = ConnectionString
oConn.Open()
CMD = oConn.CreateCommand
CMD.CommandType = CommandType.StoredProcedure
SQLStr = "sp_tblUser_Get"
'CMD.Parameters.Add("#CompanyID", SqlDbType.Int).Value = intCompanyID
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
'If strUserLogin <> "" Then
' SubSQL = " AND u.UserLogin = " & SQLS(strUserLogin)
'End If
'If intCompanyID <> 0 Then
' SubSQL = " AND u.CompanyId = " & SQLN(intCompanyID)
'End If
'SQLStr = "select u.ID, u.UserLogin, u.Name, c.CompanyName, u.CreateDate from tblUser u " & _
' " inner join tblCompany c on u.CompanyId = c.ID WHERE u.ID <> 0 " & SubSQL
CMD.CommandText = SQLStr
DA.SelectCommand = CMD
DA.Fill(DS, tblName)
CMD = Nothing
DA = Nothing
oConn.Close()
oConn = Nothing
Catch ex As System.Exception
DS = Nothing
Finally
If Not oConn Is Nothing Then
oConn.Close()
oConn = Nothing
End If
If Not CMD Is Nothing Then
CMD = Nothing
End If
End Try
Return DS
End Function
Basically lines from Dim oConn As SqlConnection = Nothing to DA.SelectCommand = CMD are used to create connection with the database and have steps to call procedure having name sp_tblUser_Get.
Then all the required parameters of this procedure are paased using lines
CMD.Parameters.Add("#LoginID", SqlDbType.VarChar, 50).Value = strUserLogin
CMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = strName
After that using SqlDataAdapter's Fill method data set is filled with the out put.
Dataset DS can contain single DataTable or multiple Datatables which depends on hot Stored procedure is written.
I am assuming it contains single datatable, then if you want to view data then in you can use.
DataTable dt= DS.Tables[0];
This dt Datatablw will contain all data.
To display that data you can use loop like mentioned below.
DataTable dt = DS.Tables[0];
foreach (DataRow dr in dt.Rows)
{
String Name = dr["FirstName"].ToString();
int Age = Convert.ToInt32(dr["Age"]);
}

How to catch oledbdatareader errors

I have this code i wrote to find out if a record exists in data base. It works well when record is found. If it isn't, it brings up an error. I would like the error to be caught in a messagebox that states "record not found" instead.
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
numeri.Read()
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
Sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(Sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(Sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
Dim recordFound As Boolean = False
While numeri.Read
recordFound = True
End While
If recordFound = False Then
MsgBox("Record Not Found")
End If

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.

How do I catch an SQL exception in a VB.NET 2010 code?

Okay, I am building a VB.NET system but I'm having troubles in catching an SQL exception in some parts of my code. In short, I am using a SELECT sql query to retrieve a particular record and I want to determine whether a record exist in a MSAccess database so that I don't retrieve 0 rows. 0 rows will lead to an exception during printing to a TextField. The following is a sample code I'm working on:
If txSearch.Text = "" Then
MsgBox("Please type the user id or use the barcode reader to scan", MsgBoxStyle.OkOnly, "Search Field Empty")
End If
'ElseIf txSearch.Text != "" Then
If txSearch.Text <> "" Then
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim dt As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim de As OleDb.OleDbDataAdapter
Dim sql As String
Dim sql1 As String
Dim temp_num As Integer
Dim cmd As New OleDb.OleDbCommand
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = new.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim search As String
search = txSearch.Text
MessageBox.Show("You are going to search for " + search + ". Click OK to continue.")
sql = "SELECT * FROM Student_Details WHERE Admin_No = '" & txSearch.Text & "'"
sql1 = "SELECT * FROM Laptop_Details WHERE Admin_No = '" & txSearch.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
de = New OleDb.OleDbDataAdapter(sql1, con)
'Dim check As Integer = sql.
'If check > 0 Then
'da.SelectCommand = cmd
ds = New DataSet("Student_Details")
da.Fill(ds, "Student_Details")
dt = New DataSet("Laptop_Details")
de.Fill(dt, "Laptop_Details")
'con.Close()
'If sql <> "" And sql1 <> "" Then
'If ds.Equals(1) And ds.Equals(1) Then
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
Dim com As New OleDb.OleDbCommand(sql, con)
Dim com1 As New OleDb.OleDbCommand(sql1, con)
Try
temp_num = com.ExecuteNonQuery
temp_num = com1.ExecuteNonQuery
Catch ex As IndexOutOfRangeException
Trace.WriteLine(ex.ToString)
End Try
con.Close()
'End If
'End If
End If
Try something like this:
if ds.Tables("Student_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
End if
if ds.Tables("Laptop_Details").Rows.Count > 0
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
End if
To help you with your comment I would do it like that:
if ds.Tables("Student_Details").Rows.Count > 0 And ds.Tables("Laptop_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
else
MsgBox("The user with id "+txSearch.Text+" does not exist")
end if
Try to use try-catch statement:
Try
Your code here for your query statements.
Catch ex as Exception MsgBox(ex.Message)End Try