VB.net Try Catch. Keep the Loop after the Catch - vb.net

I'm using Try Catch and I want to add into Form3.ListBoxes the items that are into Form2.ListBoxes in other type. But it stop adding after the Catch the exception. So I want to keep the Loop after the exception be caught!
My program get products and show the same products but in another type (Like: I have a T-shirt with a brand, but I want the "same" T-shirt in another brand).
ListBox5 are the quantity that I add in Form1. I load Images to be clearly. Form2 Listboxes are in order (ListBox1,ListBox2...). Form2 and Form3 have the same design.
Dim ConnectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Application.StartupPath & "\Tabela_Precos.xlsx; Extended Properties=Excel 12.0;")
ConnectionString.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da
For i = 0 To Form1.ListBox1.Items.Count - 1
Dim str As String = Form1.ListBox1.Items(i).ToString
Dim prod As String = str.Substring(2, 3)
da = New OleDbDataAdapter("SELECT * FROM [Mesa$] WHERE Format([Ref], ""000000000"") like '%" & prod & "%'", ConnectionString)
da.Fill(dt)
Try
ListBox1.Items.Add(dt.Rows(i).Item(0))
ListBox2.Items.Add(dt.Rows(i).Item(1))
ListBox3.Items.Add(dt.Rows(i).Item(3))
ListBox4.Items.Add(dt.Rows(i).Item(5))
ListBox5.Items.Add(Form1.ListBox5.Items(i))
ListBox6.Items.Add(ListBox4.Items(i) * ListBox5.Items(i))
Catch ex As Exception
End Try
Next
I need the Try-Catch. I'm doing a Query and if doesn't exist the line in DataBase it stop. How can I keep doing the Loop, after stop?
These are the images with program running (they are edited):
Form1
Form2
Form3

You have answered the question yourself when you say "keep the loop after the catch". You want your loop to continue, resume or move to the next iteration. All of these are VB keywords and I recommend you review For Next Statement to understand how a For loop works.
Here is one of a few ways you can accomplish this.
With no error handling, just ignore and continue:
Try
...
Catch ex As Exception
Continue For
End Try

Related

Updating DataGridView cell immediately after edited

First of all, greetings to you guys.
I've been struggling trying to update a DGV immediately after edited.
I am using Access Database at the moment and trying to edit by using OleDbCommands.
This is my code, the issue is specifically within variable numfolio.
Once the function is done, new value on cell should be +1, and the next time i click the button, it should show me new value but it doesn't do it.
What am i doing wrong?
Thanks in advance guys.
Private Sub btnCobrar_Click(sender As Object, e As EventArgs) Handles btnCobrar.Click
Dim fecha As String = DateTime.Now
Dim numfolio As Integer = VariablesDataGridView(1, 0).Value
MsgBox(numfolio)
numfolio += 1
' EnumeraciĆ³n de Folios
con.Open()
querystring = "Update Variables Set Valor ='" & numfolio & "' where Id=1"
cmd = New OleDbCommand(querystring, con)
cmd.ExecuteNonQuery()
con.Close()
End Sub
Now is there scenario that whether the record is not updated in table at all? Or is it updating after every click?
So you need to put the code in
Try
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
to trace the code execution.
To update after button click, your DGV you have to exclusively bind assigning DGV.DataSource

using loop to hide ribbon controls vb.net

I have a table for user screens.
UserID - ScreenID - Perm
I need to hide controls when the form opens with UserID and ScreenID, and I can't use the loop with condition.
This is my code:
Try
Dim da As New SqlDataAdapter
Dim ds As New DataSet
If dbconnect.State = ConnectionState.Closed Then dbconnect.Open()
da = New SqlDataAdapter("SELECT * FROM UserScreens WHERE UserID='" & UserID & "'", dbconnect)
da.Fill(ds, "Table")
If ds.Tables(0).Rows.Count > 0 Then
Dim M As DataRow = ds.Tables(0).Rows(0)
For Each ctrl As Control In Ribbon1.Controls
ctrl.Visible = M.Item("Perm")
Next
'DocIDtxt.Text = M.Item("DOCID")
End If
Catch ex As Exception
If dbconnect.State = ConnectionState.Open Then dbconnect.Close()
MsgBox(ex.ToString)
End Try
I always worry about connections first. From MS docs
"The IDbConnection object associated with the select command must be valid, but it does not need to be open. If the IDbConnection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open."
What that means is you opened your connection before the .Fill method so it will remain open. Bad! The only way your code closes the connection is if there is an error. A Finally section with .Close in your Try...End Try would do the trick but better yet use Using...End Using. This block will ensure that your objects are closed and disposed properly even if there is an error. When an object has a Dispose method it may have unmanaged resources that it must clean up.
Next, turn on Option Strict. It will be a great help pointing potential runtime errors.
Third, always use Parameters.
See inline explanation and comments.
Private Sub OpCode()
Try
'A DataTable does not have a Dispose() method so it will fall
'out of scope and be garbage collected.
Dim dt As New DataTable
'SqlConnection has a Dispose() method so use Using
Using cn As New SqlConnection("Your connection string")
'SqlCommand has a Dispose() method so use Using
Using cmd As New SqlCommand("SELECT * FROM UserScreens WHERE UserID= #UserID", cn)
'Always use Parameters. Never concatenate strings in SQL statements.
cmd.Parameters.Add("#UserID", SqlDbType.VarChar).Value = UserID
cn.Open()
'SqlDataReader has a Dispose() method so use Using
Using dr As SqlDataReader = cmd.ExecuteReader
dt.Load(dr)
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
Dim M As DataRow = dt.Rows(0)
For Each ctrl As Control In Ribbon1.Controls
'If Perm is not a boolean this line of code can't work
ctrl.Visible = CBool(M.Item("Perm"))
Next
'DocIDtxt.Text = M.Item("DOCID")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

DataGridView - Concurrency Issue When Updating or Deleting New Records

I have a problem with a DataGridView based application. After adding records to the grid, if I subsequently attempt to update or delete the new records I get the following respective errors.
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
Concurrency violation: the DeleteCommand affected 0 of the expected 1 records.
A save of the dataset is enforced in the RowValidated event.
Private Sub uxGrid_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles uxGrid.RowValidated
If IsDGVRowDirty(sender, e.RowIndex) Then
Save()
End If
End Sub
Private Sub Save()
Const procName As String = "Save"
Try
_Logger.SendLog(Me.Name & "." & procName & " - Saving alarm definition data.", NLog.LogLevel.Trace)
_myAlarmDefinitionMngr.Save(_myDataSet)
_Logger.SendLog(Me.Name & "." & procName & " - Alarm definition data has been saved.", NLog.LogLevel.Trace)
Catch ex As Exception
MsgBox("There was a problem whilst saving your changes. Please reload the form and try again. " & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical)
_Logger.SendLog(ex.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, ex)
Finally
End Try
End Sub
The client app sits on top of a relatively simple 3-tier architectural design talking to an Oracle 11 back-end, in this case comprising the elements AlarmDefinitionManager.vb, AlarmDefinitionDB.vb, AlarmDefinition.vb.
Public Function Save(ByVal myDataSet As DataSet) As Integer
Dim myOda As OracleDataAdapter
Dim myConnection As New OracleConnection
Dim myCommand As OracleCommand = Nothing
Dim myDataAdapter As OracleDataAdapter
Dim myBuilder As OracleCommandBuilder
Dim sqlStatement As String
myConnection = New OracleConnection
myConnection.ConnectionString = _connectStr
sqlStatement = "SELECT ID, LEGENDID, STATUSID, STATUSTYPEID, DIGITALSET FROM P_TBL_ALARMDEF"
If myDataSet.HasChanges Then
Try
myOda = New OracleDataAdapter(sqlStatement, myConnection)
myBuilder = New OracleCommandBuilder(myOda)
myOda.SelectCommand = New OracleCommand(sqlStatement, myConnection)
myOda.Update(myDataSet, "AlarmDefinition")
myDataSet.AcceptChanges()
myConnection.Close()
Catch ex As Exception
Throw
Finally
myCommand = Nothing
myDataAdapter = Nothing
myBuilder = Nothing
CType(myConnection, IDisposable).Dispose()
End Try
End If
End Function
My understanding of the situation is that I need to refresh the datasource in the grid, such that it reflects the changes made. In order to achieve this I wish to refresh the grid by hooking the refresh process into an event in the datagridview. However none of the events which I have tried seem to work. With each event tried thus far, I have received errors to the effect that a refresh of the datasource is not permitted from within the event. On reflection this seems logical. Is there any event associated with the datagridview which I can use to force a refresh of the datasource?
You shouldn't try to save your dataset while validating the row.
do your changes to your dataset then set your datasource to null and reattach your datasource back to the grid to force a refresh.
I personally don't like making changes to the datagrid. I prefer to edit the row outside the datagrid and send an UPDATE cmd to SQL then refresh my grid. I get more control on the changes made to the grid.
Sorted my problem. Each row change is saved directly to the database within the RowValidated event.

Better way to print out rows from a datatable in vb.net

I am new to vb.net and I am trying to query a database and print out the records in the row to the console window. I got it to work, but I have a feeling that there is a more concise way to do this. One thing that I am sure is wrong is that I had to convert the dataset to a datatable to be able to retrieve the values. Is that correct? Could you take a look at the code below (especially the for loop) and let me know what I can improve upon?
Thanks!
Module Module1
Sub Main()
Dim constring As String = "Data Source=C:\Users\test\Desktop\MyDatabase1.sdf"
Dim conn As New SqlCeConnection(constring)
Dim cmd As New SqlCeCommand("SELECT * FROM ACCOUNT")
Dim adapter As New SqlCeDataAdapter
Dim ds As New DataSet()
Try
conn.Open()
cmd.Connection = conn
adapter.SelectCommand = cmd
adapter.Fill(ds, "testds")
cmd.Dispose()
adapter.Dispose()
conn.Close()
Dim dt As DataTable = ds.Tables.Item("testds")
Dim row As DataRow
Dim count As Integer = dt.Columns.Count()
For Each row In dt.Rows
Dim i As Integer = 0
While i <= count - 1
Console.Write(row(i))
i += 1
End While
Console.WriteLine(Environment.NewLine())
Next
Catch ex As Exception
Console.WriteLine("There was an error")
Console.WriteLine(ex)
End Try
Console.ReadLine()
End Sub
End Module
Here is how I would rewrite this for a few reasons:
1) You should always use Using statements with disposable objects to ensure they are correctly cleaned up. You had a good start with the dispose commands, but this way is safer.
2) It is more efficient to use ExecuteReader than loading everything into a dataset.
3) Your try/catch statement should include object creation as well as execution.
Finally, in response to your question about datasets and datatables, that code was absolutely correct: a dataset consists of zero or more datatables, so you were just extracting the existing datatable from the dataset.
Try
Dim constring As String = "Data Source=C:\Users\test\Desktop\MyDatabase1.sdf"
Using conn As New SqlCeConnection(constring)
conn.Open()
Using cmd As New SqlCeCommand("SELECT * FROM ACCOUNT", conn)
Dim reader As SqlCeDataReader
reader = cmd.ExecuteReader()
Do While reader.Read
For i As Integer = 0 To reader.FieldCount - 1
Console.Write(reader.GetString(i))
Next
Console.WriteLine(Environment.NewLine())
Loop
End Using
End Using
Catch ex As Exception
Console.WriteLine("There was an error")
Console.WriteLine(ex)
End Try
Console.ReadLine()
End Sub
One last note: since you are just printing to the console, it doesn't matter as much, but whenever you deal with a lot of strings, especially those that are to be concatenated, you should always consider using System.Text.StringBuilder.
Here is an example rewrite of the loop that prints to the console using stringbuilder (builds the string in memory, then dumps it to the console; I have also added the field name for good measure):
Dim sbOutput As New System.Text.StringBuilder(500)
For i As Integer = 0 To reader.FieldCount - 1
If sbOutput.Length <> 0 Then
sbOutput.Append("; ")
End If
sbOutput.Append(reader.GetName(i)).Append("=").Append(reader.GetString(i))
Next
sbOutput.AppendLine()
Console.Write(sbOutput.ToString)

How to create a ComboBox autofill using SQLite Data Reader

I have two Combo-Boxes like this
I need to create an auto-fill feature for the 1st Combo-Box. It should list the EmployeeID if Search-By Field is specified as Employee-Number. Similarly it should list Employee First Name along with Last Name if the Search-By Field is Employee-Name.
How can I do this? I have no clue, I am doing this for the first time. I am using SQLite, Visual Studio 2010.
Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
' Always call Read before accessing data.
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim j As Integer = sqReader.FieldCount
While sqReader.Read()
'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
End While
'Close Reader after use
sqReader.Close()
Catch ex As Exception
'Show Message on Error
MsgBox(ex.ToString)
Finally
'At Last Close the Connection
sqConnection.Close()
End Try
I'm not sure entirely what you are asking but I think this is it.
In the SelectedIndex changed event you would have something similar to the code below. You can add an If statement to check what you are querying for and adjust your query accordingly.
Dim dt as New DataTable
Try
Using sqlConn
sqlConn.Open()
Using cmd As New SqlCommand("your query")
cmd.Connection = sqlConn
cmd.CommandType = CommandType.Text
Dim reader as SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Catch ex As SqlException
Throw New Exception(ex.Message)
End Try
With yourComboBox
.DataSource = dt
.DataValueField = "columName you want to be the value of the item"
.DataTextField = "columnName of the text you want displayed"
End With
Notice the following properties for the combo-box: AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource.
Select the appropriate AutoCompleteMode. See details on the different modes at this link.
For AutoCompleteSource, choose either ListItems (in which case the source will be the items of the ComboBox) or CustomSource. Should you choose CustomSource, set the appropriate source as the value of the ComboBox's AutoCompleteCustomSource property.
This should provide you with enough details to do what you're looking for.
The other requirements you've listed - such as taking the data from an SQLite database or changing between employee name and employee number - won't affect the way you work with the AutoComplete feature.