Call vb class to form load - vb.net

I am trying to move the following code to the VB Class, let says DataAccess.vb and then call the created VB Class using button click event, but I don't know how to do that. Does anyone here would help me to find out how to do that.
This is the code that I need to move to VB Class.
Sub LoadData()
Try
LblInvId.Text = Me._InvID.Substring(57, 27).Trim
Dim InvID As String = LblInvId.Text.Trim
Using cn As New SqlClient.SqlConnection(DatabaseConnectionForPDA.DatabaseConnection.CONNECT_RO_FOR_HMCS)
cn.Open()
Dim sql As String = String.Empty
sql &= " SELECT T1.InvID "
sql &= " , T1.ItemID"
sql &= " , T2.ItemRevNo"
sql &= " , T1.RefNo2"
sql &= " , SUM(T1.Qty) AS Qty"
sql &= " , COUNT(*) AS CRow"
sql &= " FROM [HMCS].dbo.R_Warehouse T1 "
sql &= " INNER JOIN [HMCS].dbo.M_Item T2 "
sql &= " ON T1.ItemID = T2.ItemID "
sql &= " WHERE T1.InvDate = [HMCS].dbo.f_GetInvDate() "
sql &= " AND (RTRIM(T1.InvID) = #InvID OR RTRIM(T1.RefNo2) = #InvID)"
sql &= " GROUP BY T1.InvID, T1.ItemID, T2.ItemRevNo, T1.RefNo2"
Using cmd As New SqlClient.SqlCommand(sql, cn)
cmd.Parameters.AddWithValue("#InvID", InvID)
Using dr As SqlDataReader = cmd.ExecuteReader()
Do Until dr.Read = False
LblItmNo.Text = dr("ItemID")
LblItmRevNo.Text = dr("ItemRevNo")
LblRevNo2.Text = dr("RefNo2")
LblQty.Text = dr("Qty")
LblRow.Text = dr("CRow")
Exit Do
Loop
End Using
End Using
cn.Close()
If LblRow.Text = "" Then
err.Display("在庫レコードが見つかりません", "Error Message")
Me.Close()
End If
End Using
Catch ex As Exception
err.Display(ex.Message, "Error Message")
End Try
End Sub

You can achieve that by creating an OnClick Event for the Button and referring to your function on the code side.
DataAccess.LoadData()
You will also need to pass the Textfields to the function since it will not know what for example LblInvId is in the separate class.
DataAccess.LoadData(LblInvId,...)

By assuming that you meant calling LoadData() from an event handler in another class, you have at least 2 options. One, making LoadData() shared then calling it as DataAccess.LoadData() in your click event handler. Two, creating an instance of DataAccess to access LoadData(). In your event handler:
Dim da As New DataAccess()
da.LoadData()

Related

Data Inserted, Updated or Deleted in MS Access not directly available

My app in VB.Net loads data from MS Access in a datagridview (bound with a BindingSource, but result/problem is the same if that's a DataTable).
Private Sub LecturesPrestations()
Dim myConnection = New OleDbConnection(S7ConnString)
Try
myConnection.Open()
Requete = "SELECT s.ID, u.Nom, s.DatePresta, s.TimeIn, s.TimeOut, IIF(s.TimeOut IS NULL, NULL, CDATE(s.TimeOut - s.TimeIn)) AS Duree, s.Description " &
"FROM SAV_Prestas AS s " &
"INNER JOIN Users AS u ON u.ID = s.UserID " &
"WHERE s.NumRMA = " & monRetour.ID & ";"
Call GetBindingSource(Requete, bsPrestas, RequeteOK)
If Not RequeteOK Then
MsgBox("Problème de lecture des données",, "Chargement des prestations")
Else
With Me.dgvPresta
.DataSource = bsPrestas
...
We can then insert, delete or modifiy a row in this dgv by explicit Access instructions (INSERT, DELETE, UPDATE...). The dgv is then refreshed (reload), to include these modifications.
Private Sub tsmiSuppression_Click(sender As Object, e As EventArgs) Handles tsmiSuppression.Click
If dgvPresta.CurrentCell IsNot Nothing Then
Requete = "DELETE * FROM SAV_Prestas WHERE ID = " & CInt(dgvPresta.Item("ID", dgvPresta.CurrentCell.RowIndex).Value.ToString)
RequeteSQL(Requete, RequeteOK)
If Not RequeteOK Then
MsgBox("La prestation n'a pas pu être supprimée.")
Else
Call LecturesPrestations()
End If
Else
MsgBox("Sélectionnez une prestation.", vbOKOnly, vbInformation)
End If
End Sub
Public Sub RequeteSQL(ByVal Request As String, ByRef Resultat As Boolean, Optional ByRef MsgErreur As String = Nothing)
Dim myConnection = New OleDb.OleDbConnection(S7ConnString)
Try
myConnection.Open()
Dim myCommand = New OleDbCommand(Request, myConnection)
myCommand.ExecuteNonQuery()
Resultat = True
Catch ex As Exception
Resultat = False
MsgErreur = ex.Message
Finally
myConnection.Close()
End Try
End Sub
In this way, the dgv does not display the modified data (example: deleted data still appears). It is only after a new "refresh" a few seconds later that the modifications appear.
Have you any idea what's wrong and how to solve this?
Thank you.
Have you tried to refresh your datagridview after SQL Query?
Call dgvPresta.refresh() after "Call LecturesPrestations()"
Connection performance to your DB and size might be the problem.

Visual Studio Error Index was outside the bounds of the array

I always get the following error
An unhandled exception of type 'System.InvalidOperationException' occurred in VarsityMonitoringSystem.exe
Additional information: An error occurred creating the form. See Exception.InnerException for details. The error is: Index was outside the bounds of the array.
A while ago my code was working but after I take a shower there goes the error again
Sorry I am a beginner I don't understand much in visual studio
so I got 2 forms. loginform and homeform. it seems like the code in my loginform doesnt recognize the homeform
Here is sample code, when the login button is clicked it will run this command
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\PC\Documents\Visual Studio 2012\Projects\VarsityMonitoringSystem\VarsityMonitoringSystem\LoginTesting.mdb"
con.Open()
Dim usercmd As OleDbCommand = New OleDbCommand("select * from Accounts where [Username]='" & User.Text & "'", con)
Dim userrd As OleDbDataReader = usercmd.ExecuteReader
If (userrd.Read() = True) Then
If Pass.Text = userrd("PasswordAcnt") Then
MsgBox("login successful!")
HomeForm.lblID.Text = userrd("ID")
HomeForm.lblName.Text = userrd("FirstName") & " " & userrd("MI") & " " & userrd("LastName")
HomeForm.lblGender.Text = userrd("Gender")
HomeForm.lblPosition.Text = userrd("PositionAcnt")
If userrd("Picture").ToString = "" Then
HomeForm.PictureBox1.ImageLocation = defPic
Else
HomeForm.PictureBox1.ImageLocation = userrd("Picture").ToString
End If
HomeForm.txtID.Text = userrd("ID").ToString
HomeForm.txtFName.Text = userrd("FirstName").ToString
HomeForm.txtMI.Text = userrd("MI").ToString
HomeForm.txtLName.Text = userrd("LastName").ToString
HomeForm.txtDOB.Text = userrd("BirthMonth").ToString & " " & userrd("BirthDay").ToString & " " & userrd("BirthYear").ToString
HomeForm.txtGender.Text = userrd("Gender").ToString
HomeForm.txtStreet.Text = userrd("Street").ToString
HomeForm.txtMunicipality.Text = userrd("Municipality").ToString
HomeForm.txtCity.Text = userrd("City").ToString
HomeForm.txtContact.Text = userrd("ContactNo").ToString
HomeForm.txtPosition.Text = userrd("PositionAcnt").ToString
HomeForm.txtEmail.Text = userrd("Email").ToString
HomeForm.txtEmailAdd.Text = userrd("Email").ToString
HomeForm.txtUsername.Text = userrd("Username").ToString
If userrd("Picture").ToString = "" Then
HomeForm.UploadPBox.ImageLocation = defPic
Else
HomeForm.UploadPBox.ImageLocation = userrd("Picture").ToString
End If
HomeForm.Show()
Me.Hide()
Else
MsgBox("Wrong Password!")
con.Close()
End If
Else
MsgBox("Username doesn't exist!")
con.Close()
End If
I tried to delete this code and replace it with homeform.show() but still the error persist it wont recognize the homeform
I have generated the same setup as you have one my machine. The only way I can get your issue is when the database fields does not exist. So this has nothing to do with your Form.
So to solve this you need to go into your mbd file and make sure that the Columns that you are querying for are there.

too slow in show report in vb.net 2010 using crytal report

I am using this code to show the report
Dim rpt As New CrystalReport1()
Dim sql As String
Dim where As String
If con Is Nothing OrElse con.State = ConnectionState.Closed Then
'MsgBox("closed")
OpenCon()
End If
Dim m As String
m = ""
For Each n As TreeNode In GetCheck(TreeView1.Nodes)
If n.Tag = 1 Then
m = m
Else
If m = "" Then
m = (n.Tag)
Else
m = m & ", " & (n.Tag)
End If
End If
Next
sql = "SELECT [bran_id],[f01],[f02],[f03],[f04],[f05],[f06],[f07],[f08],[bran_name],[comp_id],[comp_name],'" & dtStart.Value.Date & "' AS start_date, '" & dtEnd.Value.Date & "' AS end_date FROM [v_complain]"
If m = "" Then
MsgBox("لم يتم تحديد اى مدينة من فضلك قم بالاختيار اولا")
Exit Sub
Else
where = " WHERE bran_id in (" & m & ") and f02 between CONVERT(date,'" & dtStart.Value.Date & "',103) and CONVERT(date,'" & dtEnd.Value.Date & "',103)"
sql = sql + where
If cbF06.Checked = True Then
where = " AND (f06 like N'') or (f06 is null)"
sql = sql + where
End If
If cbF07.Checked = True Then
where = " AND (f07 like N'') or (f07 is null)"
sql = sql + where
End If
Dim dscmd As New SqlDataAdapter(sql, con)
Dim ds As New DataTable
dscmd.Fill(ds)
rpt.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rpt
CrystalReportViewer1.Refresh()
End If
con.Close()
but it's too slow to show the report in the first time. When I try to run it again without closing the window it work perfectly. Is there any way to make it faster?
Thanks
How slow it is? Several seconds?
I believe it happens do to a need to initialize underling reports 'engine'. I had similar issues and the best I could come up with was to display "Creating report, please wait..." message to a user so they. As an alternative, when you start your app, you can make a 'fake' call to create a dummy report in the background without displaying anything to a user so all required resources will be initialized by the time user is ready to create a real report.

Search Bar issue, Can not re-search VB 2008

Well I'm creating a search bar to find some patients in my school project, but when I search it works, but when I made another search it sent me the message as if the number dont exist even when it exist, this is the code of the button hope you can help me.
Private Sub cmdIDBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBuscarID.Click
Dim sqlCon As New SqlClient.SqlConnection
Dim sqlComm As New SqlClient.SqlCommand
'Ruta de la conección.
sqlCon.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Sistema para Hospitales.mdf;Integrated Security=True;User Instance=True")
'Instrucción con la que se trabajara.
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= '" & txtID.Text & "';"
'Abrir la coneccion SQL
sqlCon.Open()
Do Until txtID.Text = txtCompararID.Text
Me.PacientesBindingSource.MoveNext()
Exit Do
If EOF(True) Then KryptonMessageBox.Show("Error, no se encontro paciente.", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
Loop
If txtID.Text = txtCompararID.Text Then
txtNombres.Text = txtCompararN1.Text & " " & txtCompararN2.Text & " " & txtCompararN3.Text
txtApellidos.Text = txtCompararAp1.Text & " " & txtCompararAp2.Text
txtEdad.Text = txtCompararEdad.Text
Select Case txtCompararSexo.Text
Case Is = "F"
txtSexo.Text = "Femenino"
Case Is = "M"
txtSexo.Text = "Masculino"
End Select
Select Case TipoAfiliacionTextBox.Text
Case Is = "1"
txtTAfiliacion.Text = "Cotizante"
Case Is = "2"
txtTAfiliacion.Text = "Beneficiario"
Case Is = "3"
txtTAfiliacion.Text = "Pensionado"
End Select
txtAltura.Text = AlturaTextBox1.Text
txtPeso.Text = PesoTextBox1.Text
txtPresion.Text = PresionTextBox.Text
txtTemperatura.Text = TemperaturaTextBox.Text
Else
KryptonMessageBox.Show("No se encontro el paciente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Among other problems, because you have an Exit Do statement in the middle of your comparison loop, you will probably only ever match the first record since your do loop will execute a maximum of one time.
I am guessing that txtCompararID is databaound to your PacientesBindingSource and that the intent of your loop is move through this binding source until you find the value that matches txtID.
If that is the case, your do loop should look something more like:
' Get back to the top of the list
Me.PacientesBindingSource.MoveFirst()
Do Until txtID.Text = txtCompararID.Text
Me.PacientesBindingSource.MoveNext()
If EOF(True) Then
KryptonMessageBox.Show("Error, no se encontro paciente.", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
Exit Do
End If
Loop
In addition, you should use Using statements for your connection and command objects so that they are properly closed and disposed of when you are done using them.
For example:
Using sqlCon As New SqlClient.SqlConnection
Using sqlComm As New SqlClient.SqlCommand
... all of your code
End Using
End Using
And finally, and most importantly, you should be using a parameterized query statement in order to prevent SQL injection attacks since you are allowing direct entry of values. This statement:
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= '" & txtID.Text & "';"
should be changed to something like:
sqlComm.CommandText = "SELECT * FROM [Pacientes] WHERE IDPaciente= ?"
sqlComm.Parameters.AddWithValue("IDPaciente", txtID.text)

Looking for the best way to use ExecuteScalar()

This code works. It's based on some code I found on the internet.
Can you tell me if the coding is the best way to get a scalar value and if there is a better way can you show coding samples?
Dim objParentNameFound As Object
TextBoxParentsName.Text = ""
If TextBoxParentID.Text <> "" Then
' Display the parent's name using the parent ID. '
Dim strSqlStatement As String = "Select FatherName " & _
"From Parents " & _
"Where ID = #SearchValue"
' Set up the sql command and lookup the parent. '
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Add SqlParameters to the SqlCommand. '
.Parameters.Clear()
.Parameters.AddWithValue("#SearchValue", TextBoxParentID.Text)
' Open the SqlConnection before executing the query. '
Try
ObjConnection.Open()
Try
objParentNameFound = .ExecuteScalar()
If objParentNameFound <> Nothing Then
' Display the parent name here. '
TextBoxParentsName.Text = objParentNameFound
End If
Catch exSqlErrors As SqlException
MessageBox.Show("Sorry, I couldn't execute your query because of this error: " & _
vbCrLf & vbCrLf & exSqlErrors.Message, _
"Error")
End Try
Catch exErrors As Exception
MessageBox.Show("Sorry, there was an error. Details follow: " & _
vbCrLf & vbCrLf & exErrors.Message, _
"Error")
Finally
ObjConnection.Close()
End Try
End With
End Using
End If
The Microsoft Access Application block has some nice examples of how to use ADO.Net. In particular what you might find helpful is how they've organized tasks such as ExecuteScalar() into a series of overloaded methods making it easy to invoke the process you need.
The sample you posted would greatly benefit from separating out the concerns. In other words, take the code you use to build up the connection, command and parameters and make that a separate method or methods. This allows the code to be reused without copy& pasting it throughout your codebase. This allows your calling code to simply pass in the parameter(s) and bind the result to your text box or other controls.
Edit: Example
Assuming you use the SqlHelper.vb class you can do something like the following:
Dim searchValue As Integer = 1
Dim myConnectionString As String = "MyConnectionString"
Dim sqlStatement As String = "SELECT FatherName FROM Parents WHERE ID = #SearchValue"
Dim paramList(0) As SqlParameter
paramList(0) = New SqlParameter() With {.Value = searchValue, .ParameterName = "#SearchValue"}
TextBoxParentsName.Text = SqlHelper.ExecuteScalar(myConnectionString, CommandType.Text, sqlStatement, paramList).ToString()