Showing the messagebox only once in a loop vb.net - vb.net

I have this loop that pops out a message box every time the condition is true.
For i = 0 To DataGridView1.Rows.Count - 1
Dim c As Boolean
c = DataGridView1.Rows(i).Cells(0).Value
If c = True Then
cmd3.Connection = con
con.Open()
cmd3.CommandText = "insert into student select * from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "' delete from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "'"
dr3 = cmd3.ExecuteReader()
MessageBox.Show("Account approved.")
con.Close()
Else
End If
Next
The messagebox shows as many times as the checked row. And I want to show it just once. I relocate my messagebox everywhere but it does not work. I searched but did not come up for an answer.
I tried moving it outside the loop but the problem is, the message box still shows even the condition is false.
Thanks!

One approach would be to create a counter for successful approvals and another counter for unsuccessful approvals and display these after completing the loop. The counters are incremented in the loop depending on the result of the boolean c in each iteration.
Dim iSuccessCount As Integer
Dim iFailedCount As Integer
For i = 0 To DataGridView1.Rows.Count - 1
Dim c As Boolean
c = DataGridView1.Rows(i).Cells(0).Value
If c = True Then
iSuccessCount +=1
cmd3.Connection = con
con.Open()
cmd3.CommandText = "insert into student select * from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "' delete from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "'"
dr3 = cmd3.ExecuteReader()
con.Close()
Else
iFailedCount += 1
End If
Next
Dim sb As New StringBuilder
sb.Append(iSuccessCount.ToString)
sb.Append(If(iSuccessCount = 1, " account was ", " accounts were "))
sb.Append("approved.")
sb.Append(Environment.NewLine)
sb.Append(iFailedCount.ToString)
sb.Append(If(iFailedCount = 1, " account was ", " accounts were "))
sb.Append("not approved.")
MessageBox.Show(sb.ToString)

Related

How to know the available time and date in Reservation/CheckIn Program

I am using Visual Basic.Net and I have a problem in knowing the available Date, Time, and Room for the reservation/checkin of Hotel/Resort Reservation Program. Here in this code provided below, when I tried to reserve the specific room in a specific date and time, then restart the program, when I tried to save again with the unavailable room/date/time, the program's condition has wrongly allowed to save it again with the conflict schedule. I am using visual basic. Thank you :)
Dim varConflictSched As Boolean = False
Dim dsCheckIn As New DataSet
Dim daCheckIn As OdbcDataAdapter = New OdbcDataAdapter("SELECT * FROM tblCheckIn ORDER BY ID", MyConn)
daCheckIn.Fill(dsCheckIn, "tblCheckIn")
Dim DateTimeRangeNewIn(Val(Me.txtstaying.Text)) As DateTime
Dim DateCheckInNew As DateTime = Me.dtpCheckIn.Value
For a As Integer = 0 To dsCheckIn.Tables("tblCheckIn").Rows.Count - 1
Dim DateTimeRangeOldIn(dsCheckIn.Tables("tblCheckIn").Rows(a)("Staying")) As DateTime
REM Check if the room number is in used
If Me.cbRoomNumber.SelectedItem = dsCheckIn.Tables("tblCheckIn").Rows(a)("RoomNumber").ToString Then
REM Check if the date and time of the specified room number is in used
Dim varCheckInDate As DateTime = dsCheckIn.Tables("tblCheckIn").Rows(a)("CheckInDate")
For b As Integer = 0 To dsCheckIn.Tables("tblCheckIn").Rows(a)("Staying")
For c As Integer = 0 To Val(Me.txtstaying.Text)
DateTimeRangeOldIn(b) = varCheckInDate.AddDays(b)
DateTimeRangeNewIn(c) = DateCheckInNew.AddDays(c)
If DateTimeRangeOldIn(b).Date = DateTimeRangeNewIn(c).Date Then
If DateDiff(DateInterval.Minute, DateTimeRangeOldIn(b), DateTimeRangeNewIn(c)) <= 0 Then
varConflictSched = True
Exit For
End If
End If
Next
Next
End If
Next
If Me.txtAmount.Text = "" Or Me.txtSearch.Text = "" Or Me.txtstaying.Text = "" Or Me.txtTotal.Text = "" Or Me.cbRoomNumber.SelectedIndex = -1 Or Me.cbRoomtype.SelectedIndex = -1 Then
MessageBox.Show("Required field(s) should not be left blank" & vbCrLf & "Please try again", "NO BLANK SPACE", MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf varConflictSched = True Then
MessageBox.Show("Can't set schedule with this date." & vbCrLf & "Please insert another date.", "CONFLICT", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim DAdapter As OdbcDataAdapter = New OdbcDataAdapter("SELECT * FROM tblCheckIN ORDER BY ID ", MyConn)
Dim DSet As New DataSet
DAdapter.Fill(DSet, "tblCheckIN")
Dim NewID As Integer = DSet.Tables("tblCheckIN").Rows(DSet.Tables("tblCheckIN").Rows.Count - 1)("ID") + 1
Dim CommCheckIn As OdbcCommand = New OdbcCommand("INSERT INTO tblCheckIN (ID,CustomerID,Roomtype,RoomNumber,Amount,CheckInDate,Staying)VALUES(" & NewID & ",'" & Me.txtSearch.Text & "','" & Me.cbRoomtype.SelectedItem & "','" & Me.cbRoomNumber.SelectedItem & "','" & Me.txtAmount.Text & "','" & Me.dtpCheckIn.Value & "' , '" & Me.txtstaying.Text & "')", MyConn)
MyConn.Open()
CommCheckIn.ExecuteNonQuery()
MyConn.Close()
MessageBox.Show("Your Checking-In is succesfully saved. ", "SAVED", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.ClearAll()
End If
You don’t need looping code to find a collision.
A collision occurs when:
RequestionStartDate <= EndDate
And
RequestEndDate >= StartDate
Of course you have to add roomnumber to above, but it rather simple.
So on book button, your code will do this:
Dim strSQL As String
Dim rstData As New DataSet
Dim daRead As SqlDataAdapter
strSQL = "select * from tblCheckIn where RoomNumber = #RoomNum " & _
" AND ( (#CheckIn <= CheckOutDate) AND (#CheckOut >= CheckInDate) )"
Dim MySql As SqlCommand = New SqlCommand(strSQL, GetCon)
MySql.Parameters.Add("#RoomNum", SqlDbType.Int).Value = Me.RoomNumber.Value
MySql.Parameters.Add("#CheckIn", SqlDbType.DateTime).Value = Me.dtpCheckIn.Value
MySql.Parameters.Add("#CheckOut", SqlDbType.DateTime).Value = Me.dtpCheckOut.Value
daRead.SelectCommand = MySql
daRead.Fill(rstData)
If rstData.Tables(0).Rows.Count > 0 Then
MsgBox("you have a booking collsion")
End If
The above works since you never allow a collsion, and the above will return any record that you "over lap". this includes the cases like this:
RequestStart RequestEnd
| |
| exsiting Start/end |
or
RequestStart RequestEnd
| |
| exist Start Exist end |
or
RequestStart RequestEnd
| |
| exist Start Exist end |
in fact any combination of ANY overlap will be found by the above simple query.

Cannot open any more tables - OleDbException was unhandled

Good Day,
My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.
My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception
Thanks in advance for your time on answering my question.
here is my code for more detailed overview of my program,
Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
If shrdcon.con.State = ConnectionState.Closed Then
shrdcon.con.Open()
End If
Dim RoomNum As Integer
dtARoom.Clear()
Dim stoploop As Boolean
Dim count As Integer = 0
Dim rm1 As String
RoomAssign = ""
rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
dat.Fill(ds, "ARoom")
stoploop = False
count = 0
Do Until stoploop = "True"
RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)
ScheduleGeneration()
If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then
RoomA = RoomAssign
GenerateOfferingID()
Dim cmd1 As New OleDbCommand()
cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
cmd1.Connection = shrdcon.con
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
pipz.ExecuteNonQuery()
pipz.Dispose()
stoploop = True
Else
stoploop = False
End If
If stoploop = False Then
If count = 30 Then
stoploop = True
Else
count = count + 1
End If
End If
Loop
End Sub
This is typical error happens with Microsoft Jet engine when You have exceeded the maximum number of open TableIDs allowed by the Microsoft Jet database engine, which is 2048 with Jet3.5 engine and 1024 with older engines.
Even though you are closing the Command objects after each use, you are still using the same connection for the whole process, which actually holds the TableID's and is at some point of time exceeding the number of allowed open TableID's.
A probable solution would be to update the Jet Engine with the latest, which is available here
It might solve your problem, but if you are already using the latest engine, you have to look into other options to reduce the number of DB operations.
Try using the UpdateBatch method for applying the updates as a batch.
Hope this helps
Private Sub Command1_Click()
Dim myConnection As ADODB.Connection
Dim rsData As ADODB.Recordset
Set myConnection = New ADODB.Connection
myConnection.ConnectionString = "xxxxxxxxxxxxxxxxxxxx"
myConnection.Open
Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseClient
rsData.Open "select * from mytable", myConnection, adOpenStatic, adLockBatchOptimistic
For i = 1 To 10000
rsData.AddNew
rsData.Fields(0).Value = 1
rsData.Fields(1).Value = 2
Next i
rsData.UpdateBatch
rsData.Close
myConnection.Close
Set rsData = Nothing
End Sub
Good Evening,
Recently I encounter this type of error and i was able to resolve it by adding
con.close and call conState (a procedure conState- check below) before any insert/update or select statement
In my code i have something like
For i = 0 To DataGridView1.RowCount - 1
reg = DataGridView1.Rows(i).Cells(0).Value
Label2.Text = reg
'i added this two lines
***con.Close()***
***Call conState()***
Dim cmdcheck As New OleDbCommand("Select * from [2015/2016 UG CRF] where regno ='" & reg & "'", con)
Dim drcheck As OleDbDataReader
drcheck = cmdcheck.ExecuteReader
If drcheck.Read = True Then
GoTo A
End If
coursesFirst = String.Empty
coursesSecond = String.Empty
creditFirst = 0
creditSecond = 0
Dim cmdlevel As New OleDbCommand("Select * from [2015/2016 UG registration Biodata 5 april 16] where regno ='" & reg & "'", con)
Dim drlevel As OleDbDataReader
drlevel = cmdlevel.ExecuteReader
If drlevel.Read = True Then
level = drlevel.Item("level").ToString
faculty = drlevel.Item("faculty").ToString
program = drlevel.Item("programme").ToString
End If
...............
next
The conState is a connection testing if connection is closed is should open it again like in below
Public Sub conState()
If con.State = ConnectionState.Closed Then
con.Open()
End If
End Sub
This stop the error message
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:
OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;

if record exists update else insert sql vb.net

I have the following problem, I am developing a Clinic application using vb.net, the doctor has the ability to add medical information using checkboxes checkbox2.text = "Allergy" textbox15.text is the notes for Allergy, I want to insert the record if the patient's FileNo(Textbox2.text) doesn't exist, if it does then update the notes only, so far I was able to update it after 3 button clicks I don't know why????
any help is appreciated :)
thanks in advance
Dim connection3 As New SqlClient.SqlConnection
Dim command3 As New SqlClient.SqlCommand
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet
connection3.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=" + My.Settings.strTextbox + ";Integrated Security=True;Connect Timeout=30")
command3.CommandText = "SELECT ID,Type FROM Medical WHERE FileNo='" & TextBox2.Text & "';"
connection3.Open()
command3.Connection = connection3
adaptor3.SelectCommand = command3
adaptor3.Fill(dataset3, "0")
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
For countz = 0 To count9
Dim A2 As String = dataset3.Tables("0").Rows(countz).Item("Type").ToString
Dim B2 As Integer = dataset3.Tables("0").Rows(countz).Item("ID")
TextBox3.Text = A2
If A2 = CheckBox1.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox22.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox1.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
ElseIf A2 = CheckBox2.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox15.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox2.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Next
Else
If CheckBox1.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox1.Text & "',N'" & TextBox22.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If CheckBox2.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox2.Text & "',N'" & TextBox15.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
I think one of your problems may be related to your reducing the count of your table rows by 1 and then testing it above 0:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
Try changing to:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count
If count9 > 0 Then
Also, make sure one of the check-boxes (CheckBox1 or CheckBox2) mentioned later in your code is ticked.
-- EDIT --
Sorry - didn't explain why! The reason is that the majority of array/list like structures in .NET are zero based (i.e. start counting from 0 instead of 1).
The best course of action for you is to maximize your productivity by allowing SQL to do what it does best. Assuming you are using SQL Server 2008, the MERGE function is an excellent use case for the conditions that you have supplied.
Here is a very basic example that is contrived based upon some of your code:
CREATE PROCEDURE [dbo].[csp_Medical_Merge]
#MType int, #FileNo varchar(20), #MNotes varchar(max), #ID int, #OtherParams
AS
BEGIN
MERGE INTO [DatabaseName].dbo.Medical AS DEST
USING
(
/*
Only deal with data that has changed. If nothing has changed,
then move on.
*/
SELECt #MType, #MNotes, #FileNo, #ID, #OtherParams
EXCEPT
Select [Type], MNotes, FileNo, ID, OtherFields from [DatabaseName].dbo.Medical
) As SRC ON SRC.ID = DEST.ID
WHEN MATCHED THEN
UPDATE SET
DEST.MNOTES = SRC.MNOTES,
DEST.FileNo = SRC.FileNo,
DEST.Type = SRC.Type
WHEN NOT MATCHED BY TARGET THEN
INSERT (FieldsList)
VALUEs (FileNo, MNotes, etc, etc);
END
GO

SQL to search for encrypted values not working

I am using a button to trigger a SELECT statement, and based off of the criteria the user enters in 2 text boxes (SearchFirstTxt, SearchLastTxt), I send the Text values of those text boxes through an encryption class to find their match
I return them in a SqlDataAdapter and use it to fill a DataTable. I then use DataGridView.DataSoruce = dt to add it to the DGV.
My question: If the user leaves both text boxes blank and clicks the "SearchBtn", it doesn't select all of the records. It actually only selects records with the same encrypted values.
Here is the code:
eFirst = clsEncrypt.EncryptData(SearchFirstTxt.Text.Trim.ToUpper)
eLast = clsEncrypt.EncryptData(SearchLastTxt.Text.Trim.ToUpper)
conn.Open()
cmd.Connection = conn
If SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
Else
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
DataGridView1.DataSource = dt
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(eFirst)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(eLast)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try
How can I select ALL of the records from the Participant dbo?
The result set looks like this if the text boxes are left blank:
Edit: I switched my code, and it retrieves ALL of the results, however, now I am having difficulty returning them. (They return as encrypted, but not decrypted)
Here are the changes:
If SearchFirstTxt.Text = "" And SearchLastTxt.Text = "" Then
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
ElseIf SearchLastTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = '" & eFirst & "' ; "
ElseIf SearchFirstTxt.Text = "" Then
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = '" & eLast & "' ; "
End If
If I understand your requirements correctly, you need to add a check for the other search text when you try to search your encrypted data
If SearchFirstTxt.Text = "" AndAlso SearchLastTxt.Text <> "" Then
' Search the last only if you have a last and not a first'
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchLast", eLast)
ElseIf SearchLastTxt.Text = "" AndAlso SearchFirstTxt.Text <> "" Then
' Search the first only if you have a first and not a last'
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = #searchFirst"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
ElseIf SearchFirstTxt.Text = "" AndAlso SearchLastText.Text = "" Then
' Both emtpy so search everything'
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
Else
' Both filled so search exactly (not sure if this is needed)'
cmd.CommandText = "Select * FROM Participant " & _
"WHERE FIRST_NM_TXT = #searchFirst " & _
"OR LAST_NM_TXT = #searchLast"
cmd.Parameters.AddWithValue("#searchFirst", eFirst)
cmd.Parameters.AddWithValue("#searchLast", eLast)
End If
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Notice that I have removed your string concatenation and used a parameterized query. It is safer (avoids Sql Injection) and remove parsing problems (what if your encrypted text contains a single quote?)
Supposing then that you want to show the decrypted data you apply your deCryptData function to the values in the datatable, not to the same values used for the search (you already know the clear text)
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("FIRST_NM_TXT").ToString)
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("LAST_NM_TXT").ToString)
Next
Catch ex As Exception
MessageBox.Show("Error")
Finally
conn.Close()
End Try

Vb.net with access database: How can you help me simplify these codes?

this is my code:
'Set up connection string
Dim cnString As String
cnString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\testingDB.mdb"
Dim sqlQRY As String = "SELECT * " & _
"FROM users " & _
"WHERE firstName = '" & TextBox1.Text & "' " & _
" AND lastName = '" & TextBox2.Text & "'"
'Create connection
Dim conn As OleDbConnection = New OleDbConnection(cnString)
Try
' Open connection
conn.Open()
'create data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlQRY, conn)
'create dataset
Dim ds As DataSet = New DataSet
'fill dataset
da.Fill(ds, "user")
'get data table
Dim dt As DataTable = ds.Tables("user")
'display data
Dim row As DataRow
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 10 Then
MsgBox("10")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 9 Then
MsgBox("9")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) Then
MsgBox("SUCCESS")
Else
MsgBox("fail")
End If
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
' Close connection
conn.Close()
End Try
I'm trying it to make it simple with the same results. As you can see the if-else statements were messy but it works 100%. I do want the if-else statements to be simple and works the same as above.
Edited to check value of row(5) for DbNull values
try this for if-else statements:
Dim row As DataRow = dt.Rows(0)
Dim r5 as Object = row(5)
If IsDbNull(r5) then r5 = 0
If TextBox1.Text = row(1) And TextBox2.Text = row(2) Then
Select Case r5
Case 10, 9 : MsgBox(r5)
Case Else : MsgBox("SUCCESS")
End Select
Else
MsgBox("fail")
End If
Dim cmd as New OledbCommand
Dim sqlQRY As String = "SELECT count(*) " & _
"FROM users " & _
"WHERE firstName = #fname " & _
" AND lastName = #lname"
cmd.parameters.add("#fname",TextBox1.Text)
cmd.parameters.add("#lname",TextBox2.Text)
Dim Cnt as Integer
cmd = new oledbcommand(sqlQRy,con)
Cnt = Convert.ToInt32( cmd.ExecuteScalar())
if Cnt>=1 then
msgbox("Success")
else if
msgbox("Failure")
end if
You must be aware that your SQL could logically return more than 1 row. You need to make sure that when you read data that you intend to test in this way, that your SQL uses a primary key and return 1 row only otherwise, problems could happen when more data is added. I suggest you first ensure that exactly 1 row is returned before you perform your if test (see my comment to #SenthilKumar). You need to send appropriate message to user when no rows are found and not perform the test.
If you get exactly 1 row back, you have to ensure that the data is not null (if applicable, this depends on how your columns are defined).
Remember that data that comes form UI could be padded with blanks or be in mixed case. You may need to watch for this.
Your IF statement is not too complex as is.I am not sure what you are testing exactly, but one can observe that you are using the following conditions:
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
You can see that the the expression
dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) is common. You can assign the value to a Boolean expression and use it in your test.
You also should not include non-database processing in the scope of your try.
Just more little simpler ..
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
MsgBox("SUCCESS - " & format(dt.Rows(0).Item(5)))
Else
MsgBox("fail")
End If