Vb.net show messagebox text and variable - sql

Hi im new to vb and I want to display in my msgbox the text and variable but I can't seem to figure it out. My code is
Data = "UPDATE [Mc_Koy].[dbo].[User] SET [Balance] = [Balance] - '" & txt_fare.Text & "'WHERE [ID] = '" & txtbox_id.Text & "'"
Command = New SqlCommand(Data, Connection)
Command.ExecuteNonQuery()
Dim Data1 As String = "SELECT [Balance] FROM [Mc_Koy].[dbo].[User] Where [ID] = '" & txtbox_id.Text & "'"
Dim Command1 As New SqlCommand(Data1, Connection)
Command1.ExecuteNonQuery()
Dim dr As SqlDataReader
dr = Command1.ExecuteReader
With dr
.Read()
Dim f As Double
MsgBox("Current Balance is ", .Item(0))
.Close()
End With
But when I run it it only display the message "Current Balance is: "

I think you want to append it to the string, so use &:
MsgBox("Current Balance is " & .Item(0))

Related

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

Printing bulk reports in crystal report programmatically using vb.net and sql server

Please I am working on a School management system in vb.net and will like to print all the reports of students in a particular class in bulk at the same time programmatically. What I have done so far is, I select all the students IDs of a particular class from the studentstb which is the master table and fill the DataTable with it. I now iterate through the items using a for loop.
The bulk printing seams to work but the ranking which should have been base on a class is now repeating itself to display multiple subjects for one student.
If the number of subjects the student registered are six, it is repeating the six subjects to display about 18 of the same subjects.
Below is the code I have written:
Public Sub printbulk()
If mysqlconnectionstring.State = ConnectionState.Broken Then
mysqlconnectionstring.Open()
End If
rem instance of the crystal report
Dim rpt As CrystalReportbulkreport = New CrystalReportbulkreport
rem instance of the dataset and dataAdapter to fill the dataset for the crystal report
Dim da As New SqlDataAdapter
Dim da1 As New SqlDataAdapter
Dim ds As New DataSet
Dim dar As New SqlDataAdapter
Dim atten As New SqlDataAdapter
Dim bi As New SqlDataAdapter
Dim b As New SqlDataAdapter
Dim strclass As String = bclasss.Text
Dim strterm As String = termc.Text
Dim sess As String = sessionb.Text
rem open a printer dialogue
Me.PrintDialogbulk.Document = Me.PrintDocumentbulk
Dim dr = Me.PrintDialogbulk.ShowDialog()
if dr = DialogResult.OK then
Dim dt As New DataTable
Dim df As New SqlDataAdapter
Dim strid As String
Dim strget As String = "select studentid from studentstb where stuclass='" & strclass & "'"
df.SelectCommand = New SqlCommand(strget, mysqlconnectionstring)
df.Fill(dt)
rem iterate throuh the dataTable studentid
For Each row As DataRow In dt.Rows
For Each coll As DataColumn In dt.Columns
strid = row("studentid")
rem get the students rank in class plus some other info from assessment table
rem get student position in exam
Dim str1 As String = " SELECT * FROM (SELECT studentid,stuname,session,f_score,stuclass,term,subject,final_ca,final_exam,ca,exam_score,remarks,f_scores = SUM(f_score),position = DENSE_RANK() OVER (ORDER BY SUM(f_score) desc) FROM assessment WHERE stuclass = '" & strclass & "' and term='" & strterm & "' and session='" & sess & "' GROUP BY studentid,f_score,stuclass,term,subject,final_ca,final_exam,ca,exam_score,stuname,session,remarks) T WHERE studentid = '" & strid & "' "
da.SelectCommand = New SqlCommand(str1, mysqlconnectionstring)
rem get student remarks & conduct from the remarks table
Dim strr As String = "select class_attendance,conduct,interest,promoted_to,cremarks from remarks where studentid='" & strid & "' and stuclass='" & strclass & "' and term='" & strterm & "' and session='" & sess & "' "
dar.SelectCommand = New SqlCommand(strr, mysqlconnectionstring)
rem get student pic
Dim str11 As String = "select studentid,photo from studentstb where stuclass='" & strclass & "' and studentid='" & strid & "' "
da1.SelectCommand = New SqlCommand(str11, mysqlconnectionstring)
rem get student attendance
Dim stratten = "select attendance,reopen from attendance1 where term ='" & strterm & "' and session ='" & sess & "' "
atten.SelectCommand = New SqlCommand(stratten, mysqlconnectionstring)
rem get student bill from takehomebill table
Dim h = "select studentid,sum(amt_topay) as amt_topay from takehomebill where class='" & strclass & "' and lodging=(select lodging from studentstb where studentid='" & strid & "') group by studentid "
bi.SelectCommand = New SqlCommand(h, mysqlconnectionstring)
rem fil the datasets with the various dataAdapters
dar.Fill(ds, "remarks")
da.Fill(ds, "assessment")
da1.Fill(ds, "studentstb")
atten.Fill(ds, "attendance1")
bi.Fill(ds, "takehomebill")
rem Assign the print to the crystap report
rpt.SetDataSource(ds)
rpt.SetParameterValue("c1", strclass)
rpt.SetParameterValue("c2", strid)
rpt.PrintToPrinter(1, False, 0, 0)
Next
Next
end if
mysqlconnectionstring.Close()
End Sub
I was able to solve it by inserting a group into the crystal report. I used the studentid as the group name. I checked insert new page after the group footer.
Thank you.

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

Visual basic / sql - Unable to cast types

Ran into this error message while trying to select some records off a table.
My mind is shot right now..
Any ideas? Thanks!
myreader is,
Public myReader As SqlCeDataReader
Dim currentMatch(1) As String
cmd.CommandText = "SELECT schoolid,opponent " & _
"FROM TEAM_SCHEDULE WHERE seasonid = " & i & _
" AND gameid = " & 1 & " ORDER BY id"
myReader = cmd.ExecuteReader()
Do While myReader.Read()
currentMatch(0) = myReader.GetString(0)
currentMatch(1) = myReader.GetString(1)
Loop
Educated guess:
schoolid is defined as INT, but for some reason you are using GetString instead of GetInt32 to fetch it.
Do While myReader.Read()
currentMatch(0) = myReader.GetInt32(0).ToString()
currentMatch(1) = myReader.GetString(1)
Loop
why don't use datatable?
Public myReader As SqlCeDataReader
Dim currentMatch(1) As String
cmd.CommandText = "SELECT schoolid,opponent " & _
"FROM TEAM_SCHEDULE WHERE seasonid = " & i & _
" AND gameid = " & 1 & " ORDER BY id"
Dim dt as new DataTable
dt.load(cmd.ExecuteReader())
If you want, you can query result datatable with linq
dim QueryResults = from p as datarow in dt.rows where p.seasonid<10 select p
or select a list
dim MyObjList = (from p as datarow in dt.rows select seasonid = p.seasonid, gameid = p.gameid).ToList

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