I'm trying to connect to my database and I'm getting this error message (ex):
I've another function which opens DB and load some data, it works fine without any error... But when I try to use this, it returns me this error, the line 175 is "cn.Open()".
My connection string and Local_DB is both same as other functions which are working without errors.
Private Sub AtualizaClientes(ID As Integer)
' Local da DataBase
Dim Local_DB As String
Local_DB = "C:\Users\Heitor BASAM\Desktop\Sistema\DataBase_Sistema.accdb"
Try
Dim cn As New OleDb.OleDbConnection
cn.ConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={Local_DB}"
cn.Open()
cn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Glad you fixes your problem! Just a few bits to tidy up the code.
Always use Using...End Using with database objects that expose a Dispose method. They may be using unmanaged objects and their dispose methods must run to release these resources. The End Using takes care of this for you even if there is an error.
You can let the error bubble up to the calling code, user interface code. Wrap the call to AtualizaClientes in a Try...Catch...End Try
Private Sub AtualizaClientes(ID As Integer)
Dim Local_DB = "C:\Users\Heitor BASAM\Desktop\Sistema\DataBase_Sistema.accdb"
Using cn As New OleDb.OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={Local_DB}")
cn.Open()
End Using
End Sub
EDIT
You would add the Try...End Try to the UI code. Example...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim id As Integer = 7
Try
AtualizaClientes(id)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
I figured out the problem! I've a function when a especify textbox is changed, it calls this "AtualizaClientes" function. The problem is, when you load the form, it runs a "TextChanged" event in every textbox and trys to run the database before loading it. This was causing the error message.
To solve this problem, I made a boolean variable which returns true after loading the database. So, I changed my textchanged event to run only if this variable is true.
Related
I am working in VB and when the end user clicks on a button, I want to show a “Please wait” window (no progress update necessary) and trigger the process in the background on another thread as it might take a while to complete. I understand BackgroundWorker is the recommended approach for this, and although I have previously set up a BGW on a windows forms application, I am new to WPF and having a hard time understanding the differences.
In order to reuse some of my code, I have written a function (“DbOperation”) that executes a SQL stored procedure (from parameter) and returns a data table (or NULL if no output), and it seems to work well everywhere except in concert with my BGW.
I understand UI should only be affected by the main thread, and background threads should not touch the UI, and the BGW thread should call the long-running process.
Private Sub btnProcessReports_Click(sender As Object, e As RoutedEventArgs) Handles btnProcessReports.Click
'Set up background worker
bgw.WorkerReportsProgress = False
bgw.WorkerSupportsCancellation = False
AddHandler bgw.DoWork, AddressOf bgw_DoWork
AddHandler bgw.RunWorkerCompleted, AddressOf bgw_RunWorkerCompleted
'Show please wait window
f.Label1.Text = "Importing web reports. Please wait."
f.Show()
'Start the work!
bgw.RunWorkerAsync()
End Sub
Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs)
'Set current thread as STA
Thread.CurrentThread.SetApartmentState(ApartmentState.STA)
'Trigger job
Dim Qry As String = "EXEC [msdb].[dbo].sp_start_job N'Import Online Payment Portal Reports';"
DbOperation(Qry)
End Sub
Public Function DbOperation(ByVal qry As String, Optional ByVal type As DatabaseQueryReturnType = DatabaseQueryReturnType.NonQuery) As Object
Dim objDB As New Object
Dim dt As DataTable
Dim da As SqlDataAdapter
OpenConnection()
Dim cmd As New SqlCommand(qry)
cmd.Connection = con
If type = DatabaseQueryReturnType.DataTable Then
dt = New DataTable
da = New SqlDataAdapter(cmd)
Try
da.Fill(dt)
Catch ex As Exception
MessageBox.Show("Error retrieving data from database: " & ex.Message.ToString)
End Try
objDB = dt
dt.Dispose()
CloseConnection()
Return objDB
ElseIf type = DatabaseQueryReturnType.NonQuery Then
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error executing nonquery: " & ex.Message.ToString)
End Try
objDB = Nothing
CloseConnection()
Return objDB
End If
Return objDB
End Function
When I try running the program, it gives me “The calling thread must be STA, because many UI components require this.” on the line that calls my function. After a bit of research, I learned that you have to call SetApartmentState() before the thread is started, but this doesn’t make sense since the recommended code seems to be:
Thread.CurrentThread.SetApartmentState(ApartmentState.STA)
After adding this line, I then get “Failed to set the specified COM apartment state” on that line of code.
I have also tried commenting out the messagebox lines in the function in case it was trying to open the messageboxes on the UI thread, but it had no impact and I still got the same errors.
What am I missing in my code to get the function to run on the BGW thread?
I have already asked DevExpress this question which they have told me I have problem with my code that involves deleting a row from a DevExpress Gridview. Basically, I have a VB code-behind routine:
Protected Sub ASPxGridViewUnscheduledReviews_RowDeleting(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataDeletingEventArgs) Handles ASPxGridViewUnscheduledReviews.RowDeleting
'Dim aspxGridView As ASPxGridView = sender
Dim StatusID As Integer = CType(e.Keys("AcrStatusID"), Integer)
'delete row from ACRStatus table where AcrStatusID = StatusID
Try
lblMessage.Text = String.Empty
'Dim bl As New CYCIS_BL.Reviews
CYCIS_DL.Reviews.**UnscheduledReviewDelete(StatusID)**
Response.Redirect("ACR_RemoveUnSchReview.aspx")
Catch ex As Exception
lblMessage.Text = ex.Message
End Try
End Sub
where UnscheduledReviewDelete(StatusID) calls a Public Shared Sub from a Data Layer Reviews.vb class, which in turn executes an SQL stored procedure to delete the selected record.
The subroutine in Reviews is:
Public Shared Sub UnscheduledReviewDelete(ByVal StatusID As Integer)
Using dbManager As New DBManager(DataProviderEnums.SqlServer, SQLConnectionHelper.CONN_STRING)
Try
With dbManager
.Open()
.CreateParameters(1)
.AddParameters(0, "#StatusID", StatusID)
.ExecuteNonQuery(CommandType.StoredProcedure, "UnscheduledReviewDelete")
End With
Catch ex As Exception
Throw
End Try
End Using
End Sub
I have saved and built and rebuilt the class file and solution several times. and yet every time I build the solution the compiler throws this same error and the dynamic metadata of Reviews class shows every routine and function except for the one above. Why is it not recognizing the subroutine as part of the Reviews class?
I am attempting to read a .txt file that I successfully wrote with a separate program, but I keep getting the program stalling (aka no input/output at all, like it had an infinite loop or something). I get the message "A", but no others.
I've seen a lot of threads on sites like this one that list all sorts of creative ways to read from a file, but every guide I have found wants me to change the code between Msgbox A and Msgbox D. None of them change the result, so I'm beginning to think that the issue is actually with how I'm pointing out the file's location. There was one code (had something to do with Dim objReader As New System.IO.TextReader(FileLoc)), but when I asked for a read of the file I got the file's address instead. That's why I suspect I'm pointing to the .txt wrong. There is one issue...
I have absolutely no idea how to do this, if what I've done is wrong.
I've attached at the end the snippet of code (with every single line of extraneous data ripped out of it).
If it matters, the location of the actual program is in the "G01-Cartography" folder.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine()
MsgBox("C")
End Using
MsgBox("D")
End Sub
What does running this show you in the debugger? Can you open the Map_Cygnus.txt file in Notepad? Set a breakpoint on the first line and run the program to see what is going on.
Private BaseDirectory As String = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\"
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim WholeMap = File.ReadAllText(Path.Combine(BaseDirectory, "Map_Cygnus.txt"))
Debug.Print("Size Of Map: {0}", WholeMap.Length)
End Sub
It looks like you're using the correct methods/objects according to MSDN.
Your code runs for me in an new VB console app(.net 4.5)
A different approach then MSGBOXs would be to use Debug.WriteLine or Console.WriteLine.
If MSGBOX A shows but not B, then the problem is in constructing the stream reader.
Probably you are watching the application for output but the debugger(visual studio) has stopped the application on that line, with an exception. eg File not found, No Permission, using a http uri...
If MSGBOX C doesn't show then problem is probably that the file has problems being read.
Permissions?
Does it have a Line of Text?
Is the folder 'online'
If MSGBOX D shows, but nothing happens then you are doing nothing with WholeMap
See what is displayed if you rewite MsgBox("C") to Debug.WriteLine("Read " + WholeMap)
I have a few suggestions. Firstly, use Option Strict On, it will help you to avoid headaches down the road.
The code to open the file is correct. In addition to avoiding using MsgBox() to debug and instead setting breakpoints or using Debug.WriteLine(), wrap the subroutine in a Try...Catch exception.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine() 'dimming a variable inside a block like this means the variable only has scope while inside the block
MsgBox("C")
End Using
MsgBox("D")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that you normally should only catch whatever exceptions you expect, but I generally catch everything while debugging things like this.
I would also like to point out that you are only reading one line out of the file into the variable WholeMap. That variable loses scope as soon as the End Using line is hit, thereby losing the line you just read from the file. I'm assuming that you have the code in this way because it seems to be giving you trouble reading from it, but thought I would point it out anyway.
Public Class GameMain
Private WholeMap As String = ""
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
Using File As New StreamReader(FileLoc)
WholeMap = File.ReadLine() 'dimming the variable above will give all of your subs inside class Form1 access to the contents of it (note that I've removed the Dim command here)
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I step through this code and find out that the function is not only never called but the rest of the myBase.Load never completes what is going on here.
All outside references are displayed now. Program never hits the lines surrounded in ** and does run frmMain_Load as first item. the stepthrough icon does land ON the line that starts with reader= but never calls runAsIsQuery (breakpoints don't catch and stepthrough just evaporates). then it shows me frmMain without proccessing any other code from frmMain_Load nor from runAsISQuery
Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
sqlstring = "SELECT Nickname FROM tblBikeInfo"
reader = sql.runAsIsQuery(cnn, sqlstring) 'never fires
**If 1 = 1 Then**
'ummmm never comes back here either
End If
Extra details asked for about the other references these are in frmMain as global vars
Dim reader As OleDbDataReader
Dim sql As OLEDB_Handling 'custom class
Public cnn = MotorcyleDB.GetConnection
Function from Custom Class (OLEDB_Handling)
**Public Function runAsIsQuery(connection As OleDbConnection, SQL As String) As OleDbDataReader**
Dim reader As OleDbDataReader
Dim command As New OleDbCommand(SQL)
command.Connection = connection
Try
connection.Open()
reader = command.ExecuteReader()
Return reader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
Connection string class called (MotorcyleDB)
Public Shared Function GetConnection() As OleDbConnection
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\************\Documents\Visual Studio 2010\Projects\MotorcycleMinder\MotorcycleMinder\MotorcycleServiceLog11.accdb")
End Function
I found this:
http://blog.adamjcooper.com/2011/05/why-is-my-exception-being-swallowed-in.html
This is a snippet from the site.
If these conditions are met:
You are running on a 64-bit version of Windows (whether your application is built for 32-bit or 64-bit doesn’t matter; only the bit
depth of the OS)
You are building a WinForms app
You are debugging the application with Visual Studio (using default
options for Exception catching)
Your main form has a Load event handler
During the execution of your Load handler, an exception occurs
Then:
The exception will be silently swallowed by the system and, while your
handler will not continue execution, your application will continue
running.If you wrap your handler code in a try/catch block, you can
still explicitly catch any thrown exceptions. But if you don’t, you’ll
never know anything went wrong.
Note that all of the conditions must be met. If, for instance, you run
the application without debugging, then an unhandled exception still
be correctly thrown.
There is also a workaround on the site. But I would put the code in a try catch block, or put the entire thing in the Initializer/Constructor.
I am populating combo box from database. In debug i can see that the combo box has been populated .
here is the code
Private Sub ComboID_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboID.SelectedIndexChanged
Dim data(21) As String
Try
t_code.Text = ComboID.SelectedItem(0)
ComboID.Visible = False
data = getData(t_code.Text)
populateFields(data)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
but when i run this program i get error:Object variable or with block variable not set error
i would really appreciate your help.
Thanks
Just knowing that the combobox is populated is not enough. You should still be testing for
SelectedIndex >= 0
It is possible that SelectedIndex is changing to -1 if the user clears the selection.
Of course, it is also quite likely that getData is returning Nothing and populateFields can't handle that. It would probably throw a
If data isNot Nothing
end if
test around the populateFields call, too. It never hurts to test for edge cases.