How to associate a timer to my function..? - vb.net

I am facing another issue. I want to associate a timer to my function.
Actually what i am doing is that i am tryin to store certain values in a database. A function is such that it calculates 5 values and stores them in a database. While storing them in the database it displays them in a textbox on the form. Now i want to display them one by one which it does. But it does it so fast that i can only see the last value that it enters in the database inside the textbox.
Can i make it show all the values slowly one by one.
Private Sub dbInsert(ByVal strfile As String, ByVal hashoffile As String, ByVal p As Integer)
'parameter to the above function (ByVal strfile As String)
DbConnection()
cmd = "select * from hashtable"
da = New OleDb.OleDbDataAdapter(cmd, con)
da.Fill(ds, "values")
maxrows = ds.Tables("values").Rows.Count
TextBox1.Text = p + 1
TextBox2.Text = hashoffile
TextBox3.Text = strfile
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("values").NewRow()
dsnewrow.Item("p_id") = TextBox1.Text
dsnewrow.Item("process_name") = TextBox2.Text
dsnewrow.Item("hash_value") = TextBox3.Text
ds.Tables("values").Rows().Add(dsnewrow)
da.Fill(ds)
da.Update(ds, "values")
'MsgBox("new Item added to database")
con.Close()
'System.Threading.Thread.Sleep(1000)
End Sub

Add a Timer Control to your form
Move your code (retrieving data and displaying data) to Timer Controls tick event
Set Timer controls Interval Property as you required, to make it slow displaying values.
Call TIMERCONTROLNAME.Enabled = True to start timer.

Related

Automatically update an ID label

I am working on making a label inside my Windows Form to display new ID automatically. My label was connected to an access database and I want to make the label to display new ID after the last record of ID inside my database. For example, the last record is 'tt0005061' from Movie table. The label should display a new ID, 'tt0005062'.
Public Class Movies_Registration_Form
Dim index As Integer = 0
Private Sub Movies_Registration_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
showData(index)
End Sub
Public Sub showData(position As Integer)
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=1MDb.accdb;Persist Security Info=False;")
strSQL = "SELECT RIGHT(tconst,7) From Movie ORDER BY tconst DESC"
cmd = New OleDbCommand(strSQL, conn)
da = New OleDbDataAdapter(cmd)
da.Fill(table)
lblMovieID.Text = "tt" & table.Rows(0)(0).ToString()
End Sub
The output of the label should be in an increment form, meaning that it should be +1 from the last record inside my database.
Try with:
lblMovieID.Text = (Integer.Parse(table.Rows(0)(0)) + 1).ToString("tt0000000")

Update From DataGridView to Database

Dim sb As New MySqlConnectionStringBuilder
sb.Server = Form1.hostname.Text
sb.UserID = Form1.rootuser.Text
sb.Password = Form1.rootpassword.Text
sb.Database = Form1.hostdb.Text
sb.Port = Form1.hostport.Text
Using connection As New MySqlConnection(sb.ConnectionString)
Try
connection.Open()
Dim adapter1 As New MySqlDataAdapter(TextBox1.Text, connection)
Dim cmdb1 = New MySqlCommandBuilder(adapter1)
Dim ds As New DataSet
Dim words As String() = TextBox1.Text.Split(New Char() {" "c})
Dim tablenamewords = (words(3))
adapter1.Update(ds, tablenamewords)
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Using
It's giving me this error:
Update unable to find TableMapping['creature_template'] or DataTable 'creature_template'.
I want to select items then use a DataGrid to update them.
Note: tablenamewords = "creature_template"
You can solve this in alot of different methods.
I prefer to update the DB with a single query every time the the user ends editing a cell.
BUT FIRST you have to bind a source to your DataGridView!
How to bind a source:
Go to your application design an click on your DataGridView
Click on the pause/start like little button as shown:
Click on the "ComboBox" like textbox labeled as "chose data source" as shown and click on it:
It will open a "form", click on the Add data source as shown:
Follow the wizard, you can do it without any furhter explanation!
Well done, you almost completed it. Just go in your code, and look for this sub:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.your_table_nameTableAdapter.Fill(Me.your_db_nameDataSet.your_table_name)
End Sub
The line inside your Form1_Load Sub will upload the data inside your DataGridView, leave it there if you want it to load with the form or cut/paste it wherever you like.
Now you can add this the code to programmatically update the DB:
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Try
Dim location As Point = DataGridView1.CurrentCellAddress
Dim sqlCmd As String = "UPDATE table_name SET " & _
DataGridView1.Columns(location.X).Name.Replace("DataGridViewTextBoxColumn", "") & " = #Data " & _
"WHERE " & _
DataGridView1.Columns(0).Name.Replace("DataGridViewTextBoxColumn", "") & " = #ID"
Using myConn As New SqlConnection(My.Settings.VISURE_DA_PDFConnectionString)
myConn.Open()
Using myCmd As New SqlCommand(sqlCmd, myConn)
myCmd.Parameters.Add("#Data", SqlDbType.VarChar)
myCmd.Parameters.Add("#ID", SqlDbType.Int)
myCmd.Parameters("#Data").Value = DataGridView1.Rows(location.Y).Cells(location.X).Value
myCmd.Parameters("#ID").Value = DataGridView1.Rows(0).Cells(location.X).Value
myCmd.ExecuteNonQuery()
End Using
myConn.Close()
End Using
Catch ex As Exception
Err.Clear()
End Try
End Sub
Remarks:
location.X is the col index, location.Y is the row index
DataGridView1.Columns(0).Name This is my ID (primary key) and it is always in the first column. Change it with yours.
Don't forget to add .Replace("DataGridViewTextBoxColumn", "") whan you are getting your column name
As previously said, this code will update your DB every time the user edits one cell on your DataGridView updating only the edited cell. This is not a big issue because if you want to edit two ore more cell, every time you leave an edited cell the method DataGridView1_CellEndEdit is fired!

Adding associated double values from database when checkedlistbox item is selected

Edited
Hi I have this program where I need to display the sum of the values when read from the database. I tried something like this:
Dim selec As String
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\rose&mike\Desktop\DbSysDel3\salondbaccess.accdb")
Dim dt2 As New DataTable
selec = ""
con.Open()
For Each incheck In chcklstbx1.CheckedIndices
Dim valName As String
valName = chcklstbx1.Items.Item(incheck).ToString
Dim sqlstr2 As String = "SELECT Service_Fee FROM Service_Types WHERE [Service_Name] = '" & valName & "'"
Dim cmd As New OleDbCommand(sqlstr2, con)
Dim sum As Double = 0
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
While rdr.Read
selec += "P" + rdr("Service_Fee").ToString & ControlChars.NewLine
sum = sum + rdr("Service_Fee")
End While
End If
lblFees.Text = selec
lblTotal.Text = sum.ToString
rdr.Close()
Next
con.Close()
But all it does is display the values I want to add one by one when checked.
Here's an example of how this whole thing should be handled:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using connection As New OleDbConnection("connection string here"),
adapter As New OleDbDataAdapter("SELECT Name, Amount FROM MyTable", connection)
Dim table As New DataTable
adapter.Fill(table)
'Bind the DataTable to the CheckedListBox.
'Normally the DataSource should be set last but, in my experience, that can cause problems with a CheckedListBox.
With CheckedListBox1
.DataSource = table
.DisplayMember = "Name"
.ValueMember = "Amount"
End With
End Using
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Get all the currently checked items.
Dim checkedItems = CheckedListBox1.CheckedItems.Cast(Of DataRowView)().ToList()
'Get the item that is being checked or unchecked.
Dim currentItem = DirectCast(CheckedListBox1.Items(e.Index), DataRowView)
If e.NewValue = CheckState.Checked Then
'The current item is being checked so add it to the list.
checkedItems.Add(currentItem)
Else
'The current item is being unchecked so remove it from the list.
checkedItems.Remove(currentItem)
End If
'Sum the Amounts from each checked item.
Dim sum = checkedItems.Sum(Function(drv) CDec(drv("Amount")))
'Use sum here.
'...
End Sub
You get all the data up front, including all the text to display and all the associated numeric values. That data can be bound to the CheckedListBox as a DataTable, keeping it all packaged together.
Each time the user checks or unchecks an item in the list, you perform the calculation based on the data you already have. No need to go back to the database.
The important thing to note about the ItemCheck event is that it is raised BEFORE the item is checked or unchecked. That's why the code needs to ad the current item, or remove it from, the list of checked items.
When you bind a DataTable, each bound item is a DataRowView, i.e. an item from the table's DefaultView. You get all the checked DataRowView items, get their numeric value and sum them. Note that I've used a LINQ query to calculate the sum succinctly but you could use a loop if you wanted to, e.g.
Dim sum As Decimal = 0D
For Each drv In checkedItems
sum += CDec(drv("Amount"))
Next

passing any control as parameter in vb.net function

I have a following vb.net function as below in which i am passing a checkbox control name as parameter.Code is here
Public Function emaildata(ByVal grdv As GridView, ByVal ctrl As String, ByVal celpos As Integer) As GridView
Dim comm As OleDbCommand = New OleDbCommand()
Dim bpv As String = ""
Dim gv As New GridView
For Each gvrow As GridViewRow In grdv.Rows
Dim chkbx As CheckBox = CType(gvrow.FindControl(ctrl), CheckBox)
If chkbx.Checked Then
If bpv <> "" Then
bpv += ","
End If
bpv += gvrow.Cells(celpos).Text
comm.CommandText = "SELECT chq_num Cheque#,to_char(bpv_amt,'9,999,999,999') Amount,vch_nar Narration,bnf_nam PartyName,acc_des Bank from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "')"
comm.CommandType = CommandType.Text
comm.Connection = con
Dim da As New OleDbDataAdapter(comm)
Dim ds As New DataSet
da.Fill(ds)
gv.DataSource = ds
gv.DataBind()
End If
Next
Return gv
End Function
Problem is that i have to use same function with radiobutton also with text box and i don't want to write separate function for all type of controls.I want to detect the control as parameter and.For Example if i pass text box then function should behave like a text box and if radio then radion behaviour and if checkbox then same behaviour for this.I have these three control to pass the function and i want make a automatic detection method for these controls
You need to send ctrl as CONTROL(its a base class for all controls) as parameter.
You need to use latebinding and need to write separate cases for each control type....
Below code will work for checkbox only
Dim chkbx As CheckBox = CType(gvrow.FindControl(ctrl), CheckBox)
If chkbx.Checked Then
For textbox and radiobutton you need write additional code
Public Function emaildata(ByVal grdv As GridView, ByVal ctrl As Control, ByVal celpos As Integer) As GridView
If TypeOf ctrl Is Button Then
ElseIf TypeOf ctrl Is RadioButton Then
Else
EndIf

having trouble disabling textbox in vb.net

How do I disable a textbox the second time?
here is my code, In form load the textbox is disabled, unless the user will input an idnumber that is in the database. But what if the user will input an idnumber that is in the database then, input again another that is not,
That is where this code comes in, but it has problems, it doesnt disable the textbox in the event of a mouse click, what would be the proper way of doing this?
Private Sub Button12_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button12.MouseClick
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim sqlcon As New MySqlConnection("Server=localhost; Database=school;Uid=root;Pwd=nitoryolai123$%^;")
Dim sqlcom As MySqlCommand = New MySqlCommand("Select * from student where IDNO= '" & TextBox14.Text & "' ", sqlcon)
sqlcon.Open()
Dim rdr As MySqlDataReader
rdr = sqlcom.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("IDNO")
If (TextBox14.Text <> NoAcc) Then
MsgBox("ID Number is not yet registered!, please register first in the general information before trying to register parents information", MsgBoxStyle.Information)
TextBox7.Enabled = False
TextBox8.Enabled = False
TextBox9.Enabled = False
TextBox10.Enabled = False
TextBox11.Enabled = False
TextBox12.Enabled = False
TextBox13.Enabled = False
End If
End If
At the top of the routine ALWAYS disable the textboxes, then ENABLE them if ID NUMBER matches...
Depending upon what you're actually trying to achieve here, also in the mouse-click you may want to clear the textbox of interest if the ID matches or set it to FOCUS if it does not (to allow them to see what they entered and make changes ... maybe they just mistyped?)