Controls not showing while loading form - vb.net

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.

Related

DataGridView stay empty even if SQL request is right

So, I simply need to fill a DataGridView of a WinForm with the result of a SQL request that I tried in MySQL Workbench and works perfectly.
It's not the first time I'm doing this in this particular program and all the others worked fine. However, no matter what I do, the DataGridView stays empty.
Here goes my code :
Dim BindingName As New BindingSource, ProdSet As New DataTable
Private Sub SelectAllFacture()
ClassConfig.Connexion.Open()
ProdSet.Clear()
Dim Requete As String
Requete = "SELECT * FROM Product"
Try
Dim Cmd As New MySqlCommand
With Cmd
.Connection = ClassConfig.Connexion
.CommandText = Requete
End With
Dim Adpt As New MySqlDataAdapter(Cmd)
Adpt.Fill(ProdSet)
Catch ex As Exception
Autorisations.ErrorCheck(ex)
End Try
ClassConfig.Connexion.Close()
BindingName.DataSource = ProdSet
DataGridView.DataSource = BindingName
End Sub
To explicit what is not shown :
DataGridView is ... well, the DataGridView
Autorisations.ErrorCheck(ex) calls a Sub from another class that opens a MsgBox on error (It doesn't).
ClassConfig.Connexion is simply the connection, stored in another Class
Instead of Filling a Dataset (prodset), make it a datatable
Dim prdtable as new DataTable
then
Adpt.Fill(prdtable)
BindingName.DataSource = prdtable
Also make sure you have either already added the correct columns to the DataGridView or set:
dataGridView.AutoGenerateColumns = true

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

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.

Display data from database into DataGridView

I have two tables in my Access Database where I used to store the information of Item In and Item Out. I am displaying those data from both table in a DataGridView using a DataSet. Item In displayed in DataGridView1 and Item Out displayed in DataGridView2.
Here is my Module Function
Function to display Item In
Public Sub load_item_in()
ds_i.Reset()
Dim i_sql As String
Dim conn_i As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = access-database-file-dir")
i_sql = "SELECT * FROM item_in"
da_i = New OleDb.OleDbDataAdapter(i_sql, conn_i)
da_i.Fill(ds_i, "InventoryIn")
Form6.DataGridView1.DataSource = ds_i.Tables("InventoryIn")
Form6.DataGridView1.ReadOnly = True
End Sub
Function to display Item Out
Public Sub load_item_out()
ds_i.Reset()
Dim i_sql As String
Dim conn_i As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = access-database-file-dir")
i_sql = "SELECT * FROM item_out"
da_i = New OleDb.OleDbDataAdapter(i_sql, conn_i)
da_i.Fill(ds_i, "InventoryOut")
Form6.DataGridView2.DataSource = ds_i.Tables("InventoryOut")
Form6.DataGridView2.ReadOnly = True
End Sub
Calling out the function when button clicked
myModule.load_item_in()
myModule.load_item_out()
As you can see there, I am displaying two different DataGridView in a same form.
The problem I faced here is, I have table displayed in the DataGridView1 but no data displayed there. My DataGridView2 is able to display all data. So I am wondering either the system get confused of which data to called out because unable to display data at DataGridView1
Looks like you're using the same DataSet in both functions and resetting it before each call.
The ds_i.Reset() method in load_item_out() is clearing the data that the first method load_item_in() retrieved. Remove your DataSet "reset" and add a DataTable clear before filling the DataAdapter.
It has been awhile since I have worked in VB - though you have these in two separate sub routines I do not see where you are closing the connection to the DB. Each sub should have a connection start and a connection stop.
This is a datagridview example from a project I did in school - the main form had 4 dgv's and each had this code block with a different select statement. They all ran in the same sub but had their own try calls -
Private Sub Sponsor_Load()
'-----gridviewB----++++++
'required try catch +++++
Try
'declare variables
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
'database opened
If OpenDatabaseConnectionSQLServer() = False Then
'database fail - alert user and exit program
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
'select statement
strSelect = "SELECT * FROM TSponsors WHERE intSponsorID= " & cboSponsor.SelectedValue.ToString
'pull records from sourcetable
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
'load data table
dt.Load(drSourceTable)
'populate the datagrid view
dgvSponsor.DataSource = dt
'close source table
drSourceTable.Close()
'close db connection
CloseDatabaseConnection()
'requried try catch - +++++
Catch excError As Exception
'display error message
MessageBox.Show(excError.Message)
End Try
End Sub

How do I add htmltablecell data to database after I click submit

I created an htmltable in .aspx.vb, because I have a lot of rows that come from database and they depend on the querystring. that part is fine. But when someone makes a change in one of the cells how do I save data back to database?
Code -
Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)
Now when someone changes the price in the textbox, how do I save it in database?
This is code for submit button -
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
sqlstr = "UPDATE ???"
sqlcmd = New SqlCommand(sqlstr, sqlcnn)
sqlcmd.ExecuteScalar()
End Sub
Please answer in detail.
I would suggest using the built in grid controls. Here is a walkthrough Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
. It might be better to start with Walkthrough: Basic Data Access in Web Pages.
If you choose to move forward with HTML then here is one way to do it based on what you provided. You can add an update button and try this code in that event:
'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = #Price WHERE ID = #ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("#Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("#ID", SqlDbType.Int)
connection.Open()
'Loop through the fields returned'
For Each Key As String In Request.Form.Keys
'Make sure you only process fields you want'
If Key.StartsWith("price") Then
'Pull the ID out of the field name by splitting on the underscore'
' then choosing the second item in the array'
Dim ID As String = Key.Split("_")(1)
'Update the paramaters for the update query'
Cmd.Parameters("#ID").Value = ID
Cmd.Parameters("#Price").Value = Request.Form(Key)
'Run the SQL to update the record'
Cmd.ExecuteNonQuery()
End If
Next
connection.Close()
Let me know if you need any additional assitance. If not, please mark this as the correct answer.