Solved

In vb.net how can i ensure that the selecteditemchanged event fires every time i make a combobox selection

Posted on 2014-07-29
13
386 Views
Last Modified: 2014-08-01
I have a datagridview on a form.
I add a column to it and make the column a comboxbox selection
I format the datagrid view.
Each time i make a combobox selection on a row, that record should be deleted from my database and the table refreshed.
When i load the form - it works 1 time, if i leave the form open and make a second row choice, the selected change committed event and does not fire.
If i reload the form it works one time again then the same problem.
Relevant pieces of code detailed below, any help most welcome - i don't get any errors.

Public Sub LoadDowntimeRecords()
        'Load downtime records
        SQL.RunQuery("SELECT * FROM temptbl_Stops")
        'MsgBox(SQL.recordcount)
        SQL.SQLDA.Fill(SQL.SQLDataSet, "temptbl_Stops")
        DGVDTRecords.DataSource = SQL.SQLDataSet.Tables("temptbl_Stops")
        Dim cbo As New DataGridViewComboBoxColumn()
        DGVDTRecords.Columns.Add(cbo)
        cbo.HeaderText = "DC"
        SQL.RunQuery("SELECT DowntimeCode FROM tbl_DowntimeCodes")
        If SQL.SQLCon.State = ConnectionState.Closed Then SQL.SQLCon.Open()
        Dim SQLDR As SqlDataReader = SQL.SQLCmd.ExecuteReader()
        While SQLDR.Read = True
            cbo.Items.Add(SQLDR.Item("DowntimeCode"))
        End While
        SQL.SQLCon.Close()
    End Sub

    Public Sub RefreshDowntimeRecords()
        'Load downtime records
        SQL.RunQuery("SELECT * FROM temptbl_Stops")
        'MsgBox(SQL.recordcount)
        SQL.SQLDA.Fill(SQL.SQLDataSet, "temptbl_Stops")
        DGVDTRecords.DataSource = SQL.SQLDataSet.Tables("temptbl_Stops")
    End Sub


    Public Sub CheckTableExists()
        'Check if temp data table exists
        SQL.RunQuery("SELECT * FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME = 'temptbl_Stops' ")
        If SQL.recordcount > 0 Then
            SQL.RunQuery("DELETE FROM temptbl_Stops WHERE [ID] > 0")
        Else
            SQL.RunQuery("CREATE TABLE temptbl_Stops (ID INT IDENTITY NOT NULL PRIMARY KEY, StartDate DATETIME, StopDate DATETIME, StopTime DECIMAL(4,2), DowntimeCode NCHAR(10))")
        End If
        SQL.RunQuery("stp_UpdateTempStops")
        SQL.SQLCmd.CommandType = CommandType.StoredProcedure
    End Sub

    Private Sub DowntimeRecords_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        GetDowntimeCodes()
        FormatDGVDTCodes()
        CheckTableExists()
        LoadDowntimeRecords()
        FormatDGVDTRecords()
    End Sub

 Public Sub DGVDTRecords_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DGVDTRecords.CurrentCellDirtyStateChanged
        If DGVDTRecords.IsCurrentCellDirty Then
            DGVDTRecords.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub

    Private Sub DGVDTRecords_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles DGVDTRecords.EditingControlShowing
        'Check column number being updated
        Try
            If DGVDTRecords.CurrentCell.ColumnIndex = 5 Then
                Dim selectedComboBox As ComboBox = CType(e.Control, ComboBox)
                RemoveHandler selectedComboBox.SelectionChangeCommitted, AddressOf SelectedComboBox_SelectionChangeCommitted
                AddHandler selectedComboBox.SelectionChangeCommitted, AddressOf SelectedComboBox_SelectionChangeCommitted
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub SelectedComboBox_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)

        'Set downtime code in target column equal to column being updated
        Dim SelectedCombobox As ComboBox = CType(sender, ComboBox)
        Try
            If SelectedCombobox.SelectedItem IsNot Nothing Then
                DGVDTRecords(4, DGVDTRecords.CurrentCell.RowIndex).Value = SelectedCombobox.SelectedItem
                SendKeys.Send("{ENTER}")
            End If

            'Save downtime code to SQL database and delete updated row from temptbl_stops
            Dim ID As Integer
            Dim rc As Integer
            Dim row As Integer
            Dim col As Integer
            Dim dc As String
            row = DGVDTRecords.CurrentCell.RowIndex
            col = 4
            ID = DGVDTRecords.Rows(row).Cells(0).Value
            rc = DGVDTRecords.Rows.Count
            dc = DGVDTRecords.Rows(row).Cells(col).Value
            MsgBox("Are you sure you want to save the downtime classifcation?", vbExclamation + vbYesNo, "Message Alert")
            Dim Result As DialogResult
            Result = MsgBox("Are you sure you want to save the downtime classifcation?", vbExclamation + vbYesNo, "Message Alert")
            If Result = System.Windows.Forms.DialogResult.Yes Then
                SQL.RunQuery("UPDATE temptbl_Stops SET DowntimeCode = '" & dc & "' WHERE ID = " & ID & " ") 'update temptbl_Stops
                SQL.RunQuery("stp_UpdateMachineData") 'update tbl_MachineData
                SQL.SQLCmd.CommandType = CommandType.StoredProcedure
                CheckTableExists()
                RefreshDowntimeRecords()
                Exit Sub
            Else
                MsgBox("Information not updated, please make another selection", vbExclamation + vbOKOnly, "Message")
                If SelectedCombobox.SelectedItem = True Then
                    SelectedCombobox.Items.Clear()
                End If
            End If
            SQL.RunQuery("SELECT * FROM temptbl_Stops")
            If SQL.recordcount = 0 Then
                MsgBox("All downtime has now been classified", vbExclamation + vbOKOnly, "Message")
                MainScreen.Show()
                Me.Close()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub
0
Comment
Question by:SweetingA
  • 7
  • 5
13 Comments
 

Author Comment

by:SweetingA
ID: 40227659
oh..i am using vb express 2010
0
 
LVL 32

Expert Comment

by:sarabande
ID: 40228805
SendKeys.Send("{ENTER}")
what is the purpose of this statement?

Sara
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40229331
What control on the form are you sending the Enter key too?
0
 

Author Comment

by:SweetingA
ID: 40230002
Truth is i can't remeber - i was researched the code for the combo box somewhere on the net, can't remember where

When i comment it out my message box pops up twice, when its there it only pops up once

In any case, that's not my problem right now - problem is that the combobox selection only triggers once, unless i close and re-open the form - otherwise the small square does not dissappear from the selection as it should
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40230347
Are you using a test database with fictitious data? If you are can you zip your complete project up into a zip file with a copy of the database file itself. This is not a type of issue I will be able to debug in this manner. If you can zip the project please upload to a web site we can download the file from, a site such as Microsoft OneDrive or some other one you may have access to.
0
 

Author Comment

by:SweetingA
ID: 40230541
I have uploaded the files to onedrive, what email address do i use to give you access?
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:SweetingA
ID: 40230551
It is only test data and this is only a fraction of the files

https://onedrive.live.com/redir?resid=C91A0203A9EBBE32!108&authkey=!AFLlPD2D4TBXyR0&ithint=file%2czip

Sorry, never used it before, never knew i send you a link

If you want to keep playing around with it, In the SQL table MachineData just keep changing the downtime codes to NULL and re-run the vb.

Thanks for the support.
0
 

Author Comment

by:SweetingA
ID: 40230582
the files are vb 2010 express and SQL server 2012 express, they are all in the same directory
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40230943
Hi SweetingA;

I attempted to work on your project but I ran into a couple of problems. When I first ran the application the DGVDTRecords data grid did not fill. I then attempted to do as you stated in your post, "If you want to keep playing around with it, In the SQL table MachineData just keep changing the downtime codes to NULL and re-run the vb.", but that did not do anything different. At first when I ran it could not find the stored procedure stp_UpdateTempStops and later in my attempts it told me it could not find the stored procedure stp_UpdateMachineData. As you can see from the screen shot below it seems to be spelled differently and the other one just does not exist. I then renamed the the one that seems to be misspelled to match the db but no different. Can you please update you OneDrive with updated code.
'' These two SP's could not be found
SQL.RunQuery("stp_UpdateTempStops")
SQL.SQLCmd.CommandType = CommandType.StoredProcedure

SQL.RunQuery("stp_UpdateMachineData") 'update tbl_MachineData
SQL.SQLCmd.CommandType = CommandType.StoredProcedure

Open in new window

Screen Shot of DB Content
0
 

Author Comment

by:SweetingA
ID: 40231058
Hello Fernando,

I am very sorry, i forgot that i have several versions of SQL on my PC so i took the same names files from another directory.  See attached the updated link.

Thank you for your patience

https://onedrive.live.com/redir?resid=C91A0203A9EBBE32!109&authkey=!AP_Ag22v0spQ76I&ithint=file%2czip
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 40233430
Hi SweetingA;

I found a few issues and have correct them and it is working correctly. I have commented the areas where I made corrections and why. If you have any questions please ask.

DowntimeRecords.vb
0
 

Author Closing Comment

by:SweetingA
ID: 40234264
Top man.  Thank you ver much, worked perfectly, keep watch i have one or two other issues!
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40234272
Not a problem, glad to help.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

This script will sweep a range of IP addresses (class c only, 255.255.255.0) and report to a log the version of office installed. What it does: 1.)      Creates log file in the directory the script is run from (if it doesn't already exist) 2.)      Sweep…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now