How to Trigger Code with ComboBox Change Event - vb.net

I have a created a database containing historical stock prices. On my form I have two comboboxes, ComboBox_Ticker and ComboBox_Date. When these comboboxes are filled I want to check the database and see if the respective data exists in the database. If it does I want to change the text of a label called Label_If_Present to "In Database".
My problem occurs with the change event. I want all of this to happen once I change the data in the textboxes. I have tried both the .TextChanged and .LostFocus events. The '.TextChanged' triggers the code to early and throws and error in my SQL command statement. The `.LostFocus' event doesn't do trigger my code at all.
Here is my current code:
Public databaseName As String = "G:\Programming\Nordeen Investing 3\NI3 Database.mdb"
Public con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
Public tblName As String = "Historical_Stock_Prices"
Private Sub Change_Labels(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox_Ticker.TextChanged, ComboBox_Date.TextChanged
con.Close()
Dim dr As OleDbDataReader
con.Open()
If (File.Exists(databaseName)) Then
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = con.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
Else
Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & tblName & " WHERE Ticker = '" & ComboBox_Ticker.Text & "' " & " AND Date1 = '" & ComboBox_Date.Text & "'", con)
dr = cmd2.ExecuteReader
If dr.Read() = 0 Then
'If record does not exist
Label_If_Present.Text = ""
Else
Label_If_Present.Text = "In Database"
End If
con.Close()
End If
Else
End If
End Sub
I have successfully implemented this concept on other forms within my project. This one is slightly different and I can't figure out why I can't get this one to work.

Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value.
Then check to see that both comboboxes have values selected. Something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then

Related

Data Inserted, Updated or Deleted in MS Access not directly available

My app in VB.Net loads data from MS Access in a datagridview (bound with a BindingSource, but result/problem is the same if that's a DataTable).
Private Sub LecturesPrestations()
Dim myConnection = New OleDbConnection(S7ConnString)
Try
myConnection.Open()
Requete = "SELECT s.ID, u.Nom, s.DatePresta, s.TimeIn, s.TimeOut, IIF(s.TimeOut IS NULL, NULL, CDATE(s.TimeOut - s.TimeIn)) AS Duree, s.Description " &
"FROM SAV_Prestas AS s " &
"INNER JOIN Users AS u ON u.ID = s.UserID " &
"WHERE s.NumRMA = " & monRetour.ID & ";"
Call GetBindingSource(Requete, bsPrestas, RequeteOK)
If Not RequeteOK Then
MsgBox("Problème de lecture des données",, "Chargement des prestations")
Else
With Me.dgvPresta
.DataSource = bsPrestas
...
We can then insert, delete or modifiy a row in this dgv by explicit Access instructions (INSERT, DELETE, UPDATE...). The dgv is then refreshed (reload), to include these modifications.
Private Sub tsmiSuppression_Click(sender As Object, e As EventArgs) Handles tsmiSuppression.Click
If dgvPresta.CurrentCell IsNot Nothing Then
Requete = "DELETE * FROM SAV_Prestas WHERE ID = " & CInt(dgvPresta.Item("ID", dgvPresta.CurrentCell.RowIndex).Value.ToString)
RequeteSQL(Requete, RequeteOK)
If Not RequeteOK Then
MsgBox("La prestation n'a pas pu être supprimée.")
Else
Call LecturesPrestations()
End If
Else
MsgBox("Sélectionnez une prestation.", vbOKOnly, vbInformation)
End If
End Sub
Public Sub RequeteSQL(ByVal Request As String, ByRef Resultat As Boolean, Optional ByRef MsgErreur As String = Nothing)
Dim myConnection = New OleDb.OleDbConnection(S7ConnString)
Try
myConnection.Open()
Dim myCommand = New OleDbCommand(Request, myConnection)
myCommand.ExecuteNonQuery()
Resultat = True
Catch ex As Exception
Resultat = False
MsgErreur = ex.Message
Finally
myConnection.Close()
End Try
End Sub
In this way, the dgv does not display the modified data (example: deleted data still appears). It is only after a new "refresh" a few seconds later that the modifications appear.
Have you any idea what's wrong and how to solve this?
Thank you.
Have you tried to refresh your datagridview after SQL Query?
Call dgvPresta.refresh() after "Call LecturesPrestations()"
Connection performance to your DB and size might be the problem.

How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio)

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?
Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"
Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class
Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

VB.net Forecolor in every listview item

guys can you help me figure out how to put some forecolor in every listview item?
what I am trying to do is: I want to populate the listview with some forecolors in the items just like this
Example:
> ColumnHeader1 ColumnHeader2 ColumnHeader3
> Executive(W/Forecolor) texttexttext texttexttexttext
> Employee(Plain w/out FC) texttexttext texttexttexttext
here is my code:
Private Sub loadRemarks()
Try
jonsqlcon.Close()
jonsqlcon.ConnectionString = dllConstring
jonsqlcon.Open()
Dim selStaff As New SqlDataAdapter("SELECT * FROM StaffMember WHERE Staff_IDNo ='" & Notification.lblStaffID.Text & "'", jonsqlcon)
Dim setStaff As New DataSet
Dim accLvl As String
selStaff.Fill(setStaff)
accLvl = setStaff.Tables(0).DefaultView.Item(0).Item("AccessLVL").ToString
If accLvl = "2" Then
ListView1.ForeColor = Color.Aqua
End If
Dim loadChat As New SqlCommand("SELECT * FROM RemarksConvo WHERE Application_ID = '" & ClientAccountStatusViewer.txtClientID.Text & "' AND Room ='" & lvlStorage.Text & "'", jonsqlcon)
reader = loadChat.ExecuteReader
ListView1.Items.Clear()
Do While reader.Read = True
list = ListView1.Items.Add(reader(3).ToString)
list.SubItems.Add(reader(4).ToString)
list.SubItems.Add(reader(5).ToString)
list.SubItems.Add(reader(6).ToString)
Loop
Catch ex As Exception
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
First thing you should worry is about the Sql Injection problem of your code. Do not use string concatenation to build a query text but always a parameterized text. Not only your command is more clear but there is no way that an hacker could tamper your text to wreak havoc with your database.
Second. You can bring the information about the level of your remark's author by executing a join between the two tables. The field Staff_IDNo in both tables links the records from the remarks to the table with the info about the level of the remark's author
Finally, a ListViewItem (the object returned by ListView.Items.Add) supports the ForeColor property and you can simply set the color row by row while you add items to your listview
Dim loadChat As New SqlCommand("SELECT r.*, s.AccessLVL FROM RemarksConvo r
JOIN StaffMember s ON s.Staff_IDNo = r.Staff_IDNo
WHERE r.Application_ID = #appId
AND r.Room = #room", jonsqlcon)
loadChat.Parameters.Add("#appId", SqlDbType.NVarChar).Value = ClientAccountStatusViewer.txtClientID.Text
loadChat.Parameters.Add("#room", SqlDbType.NVarChar).Value = lvlStorage.Text)
reader = loadChat.ExecuteReader
ListView1.Items.Clear()
Do While reader.Read
list = ListView1.Items.Add(reader(3).ToString)
list.ForeColor = If(reader("AccessLvl").ToString = "2", Color.Acqua, SystemColors.WindowText)
list.SubItems.Add(reader(4).ToString)
list.SubItems.Add(reader(5).ToString)
list.SubItems.Add(reader(6).ToString)
Loop

Update record in DataGridView

I use simple SQL to modyf ACC database conected to DataGridView via dataSet.xsc. Inserting works perfect, but updateing is fail (why?)
Table have 3 columns (2 strings and one boolean represented by Checkbox).
UPDATE Tabele
SET We = True 'or False in another SQL
WHERE (Name = ?) AND (Address = ?)
"We" is checkbox in table column, I try change by mouse in DataGridView.
In code i used this line to modyf table:
Private Sub Tabela_adresowDataGridView_CellContentClick(sender As Object, _
e As Windows.Forms.DataGridViewCellEventArgs) Handles _
Tabela_adresowDataGridView.CellContentClick
If e.ColumnIndex = 2 Then
Try
With Tabela_adresowDataGridView
Me.Tabela_adresowBindingSource.EndEdit()
If .Item(e.ColumnIndex, e.RowIndex).Selected = True Then
Me.Tabela_adresowTableAdapter.UpdateQuery_Checked(.Item(0, e.RowIndex).Value.ToString, _
.Item(1, e.RowIndex).Value.ToString)
Else
Me.Tabela_adresowTableAdapter.UpdateQuery_Uncheck(.Item(0, e.RowIndex).Value.ToString, _
.Item(1, e.RowIndex).Value.ToString)
End If
Tabela_adresowDataGridView.Update()
'Me.Validate()
'Me.TableAdapterManager.UpdateAll(Me.Baza_adresowDataSet)
'Baza_adresowDataSet.AcceptChanges()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Regardless of whether the inserted Primarykey or use one simple SQL with 3th parameter for a check state. Table is not modyfied. (?)
Try to select your quert by you want and after put in your table:
Dim SelectQuery As String = "Your Query"
Dim WhereQuery As String = " WHERE (1=1)"
ElseIf BOX_toDate.Text <> Nothing Then
Name= WhereQuery & " AND TargetDate <= '" & Your value & "'"
End If
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = FunctionConnection()
cmd.Connection = con
cmd.CommandText = SelectQuery & WhereQuery
cmd.CommandType = CommandType.Text
Or like that: How to search data in all tables in database using select query in vb.net?

Update grid from a query

I have a Visual Basic 2010 application that uses a DataGridView to display a list of frequencies from a Microsoft Access 2010 database. The application uses the BindingNavigationPostionItem to allow navigation though the table.
The Move Next and Move Previous buttons move you up and down the list. The cool thing is, as you do this, I have code that sends the Frequency and Mode to my Yeasu radio and the radio then is set to that freq/mode.
This works great but, if I try to filter the DataGridView by the Service field, the ID field becomes blank and navigation does not work.
Here is the code that runs after you select what you want to filter by and you click the filter button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmbox1 As String
cmbox1 = ComboBox1.Text
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from HFUtil where service = '" & cmbox1 & "'", MyConn) '
da.Fill(ds, "HFUtil")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
BindingNavigator1.BindingSource = source1
DataGridView1.Refresh()
BindingNavigator1.Refresh()
'=========================================================
ListBox1.Items.Clear()
ListBox1.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ListBox1.Items.Add(sItemTemp)
Next
ComboBox2.Items.Clear()
ComboBox2.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ComboBox2.Items.Add(sItemTemp)
Next
End Sub
The only difference between this code and the code that runs on form load is - where clause in the data adapter.
What am I doing wrong?
I don't see in your code where you apply your filter. So, lets pretend for a second that you load your whole table into DataSet. Then next thing, you either use DataSet.DefaultView or create your custom DataView and assign this to DataSource property - you did this.
Now, all you have to do is apply row filter to the data view you use
view.RowFilter = "service = '" & cmbox1 & "'"
At this point you should only see subset of records and nothing should happen to your Id field. Because your data doesn't change.
I have suspicion, you changing your view somewhere and this is why you have problems.