Solved

Datagridview field(comboboxcolumn) not displaying properly when clicked

Posted on 2010-08-24
14
400 Views
Last Modified: 2012-05-10
I have several issues associated with clicking on a new row on a datagridview that contains a comboboxcolumn that is bound to a datatable.

I use a button to add a row to existing rows in a datagridview.  My issues are this:

1)  If I first click on the comboboxcolumn of an existing row where there is a value in the cell, when I click on the same comboboxcolumn cell of the newly added row, it doesn't remain blank.  It populates it with the text of the previously clicked row.  I would think it should remain blank.

2)  I want the dropdown to equal true whenever I click on the comboboxcolumn.  The column style is set to dropdown.  And I also use an EditingControlShowing function to make it drop down (which it does) but there are quirks where it doesn't drop down below the right cell much less the same row depending on the last cell I had focus on.

3)  Once I DO click the appropriate value of the dropdown I want to update the next two cells with values using a sub, but it doesn't execute until I exit the cell.  CellValueChanged doesn't execute until exit of the cell.

If I could resolve these three issues with a datagridviewcomboboxcolumn, it would work FLAWLESSLY for me.

I've included code I use to populate the datagridview, cellvaluechanged and other.
Private Sub LoadLogisticsLines()
        With grdviewLogistics
            .RowHeadersVisible = False
            .AutoGenerateColumns = False
            .DataSource = dvLogisticsLines
            .EditMode = DataGridViewEditMode.EditOnEnter
        End With
        With display_order
            .DataPropertyName = "display_order"
            .HeaderText = "Ord"
            .Width = 30
            .ReadOnly = True
            .Visible = True
        End With
        With action
            .DataSource = dtActionTypes
            .ValueMember = "ID"
            .DisplayMember = "Description"
            .DataPropertyName = "action_type_description"
            .HeaderText = "Action Type"
            .Width = 80
            .ReadOnly = False
        End With
        With pickup_delivery_index
            .DataSource = dvGlobalShippingAddresses
            .ValueMember = "shipping_address_id"
            .DisplayMember = "company_description"
            .DataPropertyName = "pickup_delivery_id"
            .HeaderText = "Pickup/Delivery Locations"
            .Width = 210
            .ReadOnly = False
        End With
        With pickup_delivery_address
            .DataPropertyName = "pickup_delivery_address"
            .HeaderText = "Address"
            .Width = 160
            .ReadOnly = False
        End With
        With pickup_delivery_city_state
            .DataPropertyName = "pickup_delivery_city_state"
            .HeaderText = "City / State"
            .Width = 140
            .ReadOnly = False
        End With
        With pickup_delivery_billing_type_description
            .DataSource = dvLoadUnit
            .ValueMember = "load_unit_id"
            .DisplayMember = "description"
            .DataPropertyName = "billing_type_id"
            .HeaderText = "Billing Type"
            .Width = 70
            .ReadOnly = False
        End With
        With pickup_delivery_billing_count
            .DataPropertyName = "billing_count"
            .HeaderText = "Unit Count"
            .Width = 70
            .ReadOnly = False
            .DefaultCellStyle.Format = "##,##0.00"
        End With
        With pickup_delivery_billing_rate
            .DataPropertyName = "billing_rate"
            .HeaderText = "Rate"
            .Width = 70
            .ReadOnly = False
            .DefaultCellStyle.Format = "##,##0.0000"
        End With
        With pickup_billing_sub_total
            .DataPropertyName = "billing_sub_total"
            .HeaderText = "Sub Total $$"
            .Width = 80
            .ReadOnly = True
            .DefaultCellStyle.Format = "##,##0.00"
        End With
    End Sub

    Private Sub grdviewLogistics_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdviewLogistics.CellValueChanged
        If Activating Then Exit Sub
        Dim xCell As DataGridViewCell = grdviewLogistics(e.ColumnIndex, e.RowIndex)
        Dim xCellName As String = xCell.OwningColumn.Name
        Select Case xCellName
            Case "pickup_delivery_index"
                Dim drv As DataRowView = dvLogisticsLines(e.RowIndex)
                Dim da As New SqlDataAdapter
                Dim ds As New DataSet
                Dim dt As New DataTable
                da.SelectCommand = New SqlCommand
                da.SelectCommand.Connection = TSFConnection
                da.SelectCommand.CommandType = CommandType.StoredProcedure
                da.SelectCommand.CommandText = "SPS_SelectShippingAddressEntry"
                da.SelectCommand.Parameters.Add(New SqlParameter("@CompanyID", glCompany))
                da.SelectCommand.Parameters.Add(New SqlParameter("@ShippingAddressID", grdviewLogistics.CurrentCell.Value))
                da.Fill(ds, "shipping_addresses")
                dt = ds.Tables(0)
                If dt.Rows.Count > 0 Then
                    drv.BeginEdit()
                    drv("pickup_delivery_address") = dt.Rows(0)("shipping_address1").ToString
                    drv("pickup_delivery_city_state") = dt.Rows(0)("shipping_city").ToString & ", " & dt.Rows(0)("shipping_state").ToString
                    drv.EndEdit()
                End If
            Case "billing_rate", "billing_count"
                Dim index As Integer = grdviewLogistics.CurrentRow.Index
                If (index = -1) Then
                    Exit Sub
                End If
                Dim drv As DataRowView = dvLogisticsLines(index)
                drv.BeginEdit()
                drv("billing_sub_total") = drv("billing_rate") * drv("billing_count")
                drv.EndEdit()
        End Select
        bSave.Enabled = True
    End Sub

    Private Sub grdviewLogistics_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdviewLogistics.EditingControlShowing
        Select Case grdviewLogistics.CurrentCellAddress.X
            Case 1, 2, 5 ' Action Type, Pickup/Delivery Index , Billing Rate Type
                Dim cbo As ComboBox = CType(e.Control, ComboBox)
                If Not cbo Is Nothing Then
                    If Not cbo.DroppedDown Then
                        cbo.DroppedDown = True
                    End If
                End If
        End Select
    End Sub

Open in new window

0
Comment
Question by:TSFLLC
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
14 Comments
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33513562
As i understand in column 1,2,3 you have datagridview combobox...
1.To remain blank the next comboboxcell you have to declare it as new Comboboxcell
2.as for the 2 and 3 question you have to add and removea dropdown hander ...
i will give an example:
 Private combo As ComboBox
    Private Sub DataGridView_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView.EditingControlShowing

        Try

            combo = CType(e.Control, ComboBox)

            If (combo IsNot Nothing) Then


                RemoveHandler combo.DropDownClosed, New EventHandler(AddressOf ComboBox_DropDownClosed)
                AddHandler combo.DropDownClosed, New EventHandler(AddressOf ComboBox_DropDownClosed)


                RemoveHandler combo.DropDown, New EventHandler(AddressOf ComboBox_DropDown)
                AddHandler combo.DropDown, New EventHandler(AddressOf ComboBox_DropDown)


            End If


        Catch ex As InvalidCastException

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

    End Sub


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

        
        Try

            If Me.DataGridView.CurrentRow.Cells(1).IsInEditMode Or Me.DataGridView.CurrentRow.Cells(2).IsInEditMode Or Me.DataGridView.CurrentRow.Cells(3).IsInEditMode Then
                

                

                Dim CustID As Integer = combo.SelectedValue
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                Dim bs As New BindingSource
                bs.DataSource = Me.YourDataset
                bs.DataMember = "YourDataTable"
                

                Dim col As New DataGridViewComboBoxCell
                col = Me.DataGridView.CurrentRow.Cells(1)

                col.DataSource = bs
                col.DisplayMember = "......."
                col.ValueMember = "........"
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Do the same for col2,col3

            End If

        Catch ex As ArgumentException

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

    End Sub


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

        Try

            Dim CustID As Integer = Me.DataGridView.CurrentRow.Cells(1).Value
           
            If Me.DataGridView.CurrentRow.Cells(1).Value IsNot DBNull.Value AndAlso Me.DataGridView.CurrentRow.Cells(1).Value IsNot Nothing Then


                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                Dim bs As New BindingSource
                bs.DataSource = Me.YourDataset
                bs.DataMember = "YourDataTable"
                

                Dim col As New DataGridViewComboBoxCell
                col = Me.Flights_PersonnelDataGridView.CurrentRow.Cells(1)

                col.DataSource = bs
                col.DisplayMember = ".........."
                col.ValueMember = ".........."
                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

            End If

        Catch ex As InvalidCastException

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

    End Sub

Open in new window

0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33513726
Flights_PersonnelDataGridView    (forget this)
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33514001
comboboxes i mean 1,2,5 Declare each cell as new comboboxcell..as i mentioned above....
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:TSFLLC
ID: 33516068
jtoutou,

I've been analyzing your code and attempting to implement it even though I don't understand the reasoning behind using it.

Where you have 'bs.DataSource = Me.YourDataset' I am using a dataview and not a dataset.
Also, in attempting to replace 'bs.DataMember = "YourDataTable"' with my datatable 'dtGlobalShippingAddresses' I get an error saying.... 'DataMember property 'dtGlobalShippingAddresses' cannot be found on the DataSource.'

My main issue is 'Why is this necessary and what is it suppose to do for me?'.

It makes no sense to me that when I append my dataview with a new row and I click on the shipping_address column that it wants to automatically display a value in it.  Yet if I don't cause the dropdown to occur and I tab to the next field, this value is not even used and the column ends up being cleared to blank.

What gives?
Thanks!
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33516208
My previous code just populates each combobox datagridviewcell individually
other option is on a cell click event to insert this kind of code...this suupose to clear any selection when you attempt to drop down your combobox
 Private Sub MYDataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles MyDataGridView.CellClick
        If e.ColumnIndex = 1 or e.ColumnIndex = 2 Or e.ColumnIndex = 5 Then
 
    
      Dim MYControl As DataGridViewComboBoxEditingControl = DirectCast(MYDataGridView.EditingControl, DataGridViewComboBoxEditingControl)

        If Not MYControl Is Nothing Then
            MYControl.SelectedIndex = -1
        End If
 End If
End Sub

Open in new window

0
 

Author Comment

by:TSFLLC
ID: 33519925
I have had this in the back of my mind.... two of the three dataviews I am using as bindingsources for the comboboxcolumns do not have a UNION SELECT 0, NULL, etc. when creating the list.  Because of this, clicking on
the cell automatically wants to put something in the cell, and that ends up being the LAST company_description I had clicked on....in a row/cell different from the newly created one that is blank.

Therefore, I decided to modify the stored procedure being used to get the record list where I am using UNION SELECT .... and putting a blank  row as row 0.

This took care of the problem COMPLETELY in regards to the cell being populated with some erroneous value.

I also modified your last piece of code to automatically drop down the comboboxes even when the first click I make is to change rows.  Works great.

The only thing I need to know now is how do I capture the click on the combobox dropdown so that I can populate two cells with address/city/state info using a select statement from the valuemember??
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33519970
So you need acording to combobox selection to fill other cells with a certain Value Correct?
0
 

Author Comment

by:TSFLLC
ID: 33520001
Correct.

When I select from the dropdown I immediately want to run a sub that selects an address and city/state using a sql select statement.
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33520019
If So put the selected Value Of the combobox in a WHERE Clause in your Select Statemet and set the value in the correct Rows(e.rowindex).Cell("YourCell")
0
 

Author Comment

by:TSFLLC
ID: 33520054
I've got that part.

What I don't know how to do is what event do I use to capture the click on the dropdown so that I can create what you just posted.

??  datagridview.comboboxcolumn.dropdown.click

See where I'm going?
0
 
LVL 18

Accepted Solution

by:
John (Yiannis) Toutountzoglou earned 500 total points
ID: 33520078
Here you have to add your qwn handler as my first comment
   Private Sub DataGridView_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView.EditingControlShowing

        Try

            combo = CType(e.Control, ComboBox)

            If (combo IsNot Nothing) Then


                RemoveHandler combo.DropDownClosed, New EventHandler(AddressOf ComboBox_DropDownClosed)
                AddHandler combo.DropDownClosed, New EventHandler(AddressOf ComboBox_DropDownClosed)


              

            End If


        Catch ex As InvalidCastException

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

    End Sub


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

        
        Try

            If Me.DataGridView.CurrentRow.Cells(1).IsInEditMode Then
                

                

                Dim CustID As Integer = combo.SelectedValue
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
               'Your SelectStatemnt Here With the Where Clause....Execute.Reader e.t.c
                

                

            End If

        Catch ex As ArgumentException

        Catch ex As Exception

            MsgBox(ex.ToString)

        End Try

    End Sub

Open in new window

0
 

Author Comment

by:TSFLLC
ID: 33520110
AAAHHHH!

Just like to code you added above only a little different.  I've never used EditingControlShowing.

Let me put it in there and test.    Thanks!!!
0
 

Author Comment

by:TSFLLC
ID: 33520311
WORKS PERFECTLY!!!

This helps me out like you don't know.

I know I can do anything now associated with a datagridviewcombobox & it's dropdown.


Wish there were more points available.

Won't forget you!

Phil Tate
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
ID: 33520506
very very welcome....
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 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