Visual Studio Error Index was outside the bounds of the array - vb.net

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.

Related

Call vb class to form load

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()

Error connecting to Oracle database (ORA-12560)

I'm hitting the error mentioned in the Title when attempting to connect to the database in the VB.net application I'm developing. I know it's not the listener or any service issue, as I'm able to connect to the same database, with the same credentials in a different application I developed (I ran that application after failing to connect with the one I'm developing, so it's not the Windows Event log).
Both use an Oracle.DataAccess.Client.OracleConnection to reference an existing ODBC connection. The connections are created and opened in slightly different ways so I figure it's something in my VB code that's causing the issue, but I can't for the life of me think of what it might be.
The non-functional code:
Public Function EstablishCon(ByVal odbc As String,
ByVal uname As String,
ByVal pass As String) As Oracle.DataAccess.Client.OracleConnection
'
Dim constr As String
Dim scon As Oracle.DataAccess.Client.OracleConnection = Nothing
Try
constr = "Data Source=" & odbc & ";User Id=" & uname & ";Password=" & pass & ";"
scon = New Oracle.DataAccess.Client.OracleConnection(constr)
scon.Open()
Catch ex As Exception
MsgBox("Encountered an error while creating the Oracle connection string and opening the connection. This will cause the application to be unable to access any data." _
& " As such the application will close following the closure of this error message." & Chr(10) & Chr(10) & "Error Details: " & ex.Message, vbOKOnly, _
"Critical Error: Failed to the Oracle Database")
scon.ConnectionString = Nothing
End Try
Return scon
End Function
Whereas my working code looks like:
Private Sub MainWin_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'
'Dim scmd As New SqlClient.SqlCommand
Dim QTxt As String = ""
Dim ConStr As String = "Data Source=existing ODBC connection name;User Id=user_name;Password=pass;"
Dim scon As New Oracle.DataAccess.Client.OracleConnection(ConStr)
Dim d As New DataStore
Dim scmd As New Oracle.DataAccess.Client.OracleCommand
Dim odr As Oracle.DataAccess.Client.OracleDataReader
'Setup the datatable in d
Try
d.DT.Columns.Add("App_Type")
d.DT.Columns("App_Type").DataType = GetType(String)
d.DT.Columns.Add("CPU_Seconds")
d.DT.Columns("CPU_Seconds").DataType = GetType(Double)
'd.DT.Columns.Add("Pct_Of_CPU")
'd.DT.Columns("Pct_Of_CPU").DataType = GetType(Double)
d.DT.Columns.Add("RunDate")
d.DT.Columns("RunDate").DataType = GetType(Date)
Catch ex As Exception
Me.Errors.Text = "Encountered an error setting up the data table that will receive the query data. Details: " & ex.Message
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.Status.Text = Now() & " - Building the SQL executor"
Me.Refresh()
'Build the query executor
Try
scmd.CommandType = CommandType.Text
scmd.Connection = scon
'Capture the query text
QTxt = 'Some text that makes a valid query
scmd.CommandText = QTxt
Catch ex As Exception
Me.Errors.Text = "An error occurred while building the SQL Executor. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.ProgBar.Step = 5
Me.ProgBar.PerformStep()
Me.Status.Text = Now() & " - Connecting to the database" & Chr(10) & Me.Status.Text
Me.Refresh()
Try
'Open the connection
scon.Open()
Catch ex As Exception
Me.Errors.Text = "An error occurred while opening the SQL connection. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon.Close()
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
'Some more stuff that's not relevant
End Sub
Sorry for the messy formatting, I spent 15 minutes trying to keep the two blocks of code separate, but StackOverflow just wasn't having it.
So the only real difference between the two is that one filled in the connection string when declaring the Connection variable, and the other does so later and in a separate function. The function aspect doesn't appear to factor as the error is thrown and caught inside the function. I
So the problem was how I was invoking the form that calls for the function. I had use .Show rather than .ShowDialog.
This resulted in the form variables (which hold the values that get passed in as odbc, uname, & pass) being cleared prior to hitting the Shown event (where the connection function is invoked).

Binding Source Filter not working in DGV

I'm having a problem with the binding source on a DGV . The message is "DataMember Property 'nodes' cannot be found on the dataSource " The column count is 14 after setting the table to the datasource. The error occurs on the line nodesDataGridView.DataSource = bsNodes. If I break before the error and then hover on the ds it does show that table nodes is in the datasource. I've used code similiar to this to setup other DGV's and I don't see any difference in this one.
if I remove these statements, I don't get the error but of course it is not filtered):
nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = " & Globals.customer_id
I should probably mention that I added company_number after the grid was completed and working. It was setup for a single company code but now I'm having to add the requirement to support multiple companies in the database.
Any ideas?
Thanks,
Vic
' Setup objects for loading the summary grid
Dim sqlNodes As String = "Select *From nodes order by display_sequence"
Dim comm As MySqlCommand = New MySqlCommand(sqlNodes, m_cn1)
Dim daNodes As MySqlDataAdapter = New MySqlDataAdapter(comm)
Dim dsNodes As DataSet = New DataSet()
dim bsNodes As New BindingSource
Try
AddHandler ButtonSaveChanges.Click, AddressOf ButtonSaveChanges_Click
dsNodes.Clear()
daNodes.Fill(dsNodes, "nodes")
m_cn1.Close()
nodesDataGridView.DataSource = dsNodes
nodesDataGridView.DataMember = "nodes"
bsNodes.DataSource = dsNodes.Tables("nodes")
Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = " & Globals.customer_id
Catch ex As Exception
MessageBox.Show("Failed to load summary grid" & vbCrLf & vbCrLf & ex.ToString)
End Try
try to filter like this
bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"
EDIT:
bsNodes.DataSource = dsNodes.Tables("nodes")
nodesDataGridView.DataSource = bsNodes '<- you set dsNodes(Dataset) this should be the BindingSource not Dataset
nodesDataGridView.DataMember = "nodes"
Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
'nodesDataGridView.DataSource = bsNodes
bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"

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.

VB Custom login page. Incorrect syntax near '.'.

I am creating a custom log in page using VB in Visual Studio. Every time I try logging in, however, I get the following error:
"Incorrect syntax near '.'".
When I put in the wrong username/password combo it recognizes this, but when it is right it will get this error and fail to log in.
Private Function VerifyLogin(ByVal UserName As String) As Boolean
Try
Dim cnn As New Data.SqlClient.SqlConnection
cnn.ConnectionString = My.MySettings.Default.RedwoodConnectionString.Replace(";Integrated Security=True", ";Integrated Security=False") & UserSetting
Dim cmd As New Data.SqlClient.SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT COUNT (principal_id) FROM _ sys.database_principals WHERE(name = '" & UserName & "')"
cnn.Open()
Dim i As Integer
i = cmd.ExecuteScalar()
cnn.Close()
If (i > 0) Then Return True
Return False
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Error: " & ex.Message & vbNewLine & "Location: VerifyLogin() in Login.vb" & vbNewLine & "Returned value: False")
Return False
End Try
End Function
Look at this portion of your sql:
FROM _ sys.database_principals
See the mistake there? It thinks the _ is the full table name and sys is an alias. At this point, .database_principals is no longer valid, hence your error.
And while we're at it, you really need to fix the sql injection vulnerability!!