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
Related
as the title says it's not saving
Code
Try
connection()
Dim cmd As New SQLiteCommand
'cmd.Connection = connection()
cmd.CommandType = CommandType.Text
cmd.CommandText = "UPDATE Emp SET Value = Value +1 WHERE Id='1'"
cmd.ExecuteNonQuery()
cmd.Dispose()
connect.Close()
MsgBox("Data Has been Saved !")
Catch ex As Exception
MsgBox("Failed when saving data")
End Try
Basically im incrementing Log by 1 if the Id is equal to X.
the error seems to be in "cmd.ExecuteNonQuery()"
Table name : Emp
Value = Integer
Id = Integer
Comments and explanations in-line.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
'Get your connection locally
Using cn As New SQLiteConnection("Your connection string")
'The using blocks ensure that your database objects are
'closed and disposed even if there is an error.
'You have put your Id in single quotes '1'
'This indicates that it is a string
'Usually an Id is a number, check your database
Using cmd As New SQLiteCommand("UPDATE Emp SET Value = Value +1 WHERE Id='1'", cn)
'You can pass your command text and the connection
'directly to the command constructor
cmd.CommandType = CommandType.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MsgBox("Data Has been Saved !")
Catch ex As Exception
MsgBox("Failed when saving data. " & ex.Message)
End Try
End Sub
If your ID in your Where clause is not a literal and comes from user input then you need to use parameters.
I don't know if this is a bug or anything... but i created another project then copy and paste everything.
weird thing is it works! but the original one still doesn't. i mean i copy and paste everything from the designer to the code and the copy worker while the original doesn't
I'm using VS 2013 Updated 5...
thank you both of you.
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.
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
I am trying to Load the form as
Dim f as New Form2
f.show()
The form is getting loaded but it doesnt show all the controls. I have two buttons and two text box. Both the buttons and one text box appears as transparent. The form appears like that till the current subroutine has ended.
Moreover, the form on loading shall display the text fetched from database and shall display the text (fetched again at equal interval from db) unless user explicitly closes the application. That logic also is in Form2_Load event.
How do I write the logic such that form2 displays properly and gets the text from db at regular interval.
I am creating a dictionary like application for healthcare domain. It works in two mode. One of the mode is ribbon mode, where a form is created (the form is marked as topmost) which should display the term and definition as long as application is alive. Hence you see an endless loop. Once user presses the close button or presses X, the application will close.
I was playing around with the code and moved it from Load even to shown event. However the issue persists.
Private Sub Form2_Shown(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Shown
Dim myConnection As OleDbConnection = New OleDbConnection
Dim idSelected, queryGetWordDef, totalRows
Dim rowReturned, queryGetMaxID, provider, ipath, dataFile, connString As String
Dim dict() As String
Dim dr1 As OleDbDataReader
Dim dt As DataTable = New DataTable
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
ipath = Application.StartupPath
dataFile = ipath & "\Database\database1.mdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
queryGetMaxID = "SELECT ID FROM Table1"
myConnection.Open()
Dim cmd As OleDbCommand = New OleDbCommand(queryGetMaxID, myConnection)
Try
dr1 = cmd.ExecuteReader()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
dt.Load(dr1)
totalRows = dt.Rows.Count
While True
idSelected = dt.Rows.Item(CInt(totalRows * Rnd()) + 1)(0)
queryGetWordDef = "SELECT Word & ""#"" & Meaning FROM Table1 WHERE ID = " & CStr(idSelected)
cmd = New OleDbCommand(queryGetWordDef, myConnection)
Try
rowReturned = cmd.ExecuteScalar()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
dict = rowReturned.Split("#")
Me.txtBoxDefinition.Text = dict(1)
Me.txtBoxTerm.Text = dict(0)
Thread.Sleep(5000)
End While
End Sub
Picture of form attached for more clarity.
As mentioned, you have an infinite loop. The loop is entered before the form is completed being created.
To achieve what you are requesting you need to look at backgroundworker
You can use this in conjunction with the timer to trigger the backgrounderworker doWork() event.
The link also has an example of how to update the text on a form as well.
You have an endless loop in your Shown event handler. That code is executed on the UI thread and it never ends, so you can never do anything else on the UI thread.
Get rid of that loop altogether. If you want to do something every 5 seconds then use a Timer with an Interval of 5000.
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.