Solved

Datagridview field(comboboxcolumn) not displaying properly when clicked

Posted on 2010-08-24
14
394 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
  • 8
  • 6
14 Comments
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
Comment Utility
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
Comment Utility
Flights_PersonnelDataGridView    (forget this)
0
 
LVL 18

Expert Comment

by:John (Yiannis) Toutountzoglou
Comment Utility
comboboxes i mean 1,2,5 Declare each cell as new comboboxcell..as i mentioned above....
0
 

Author Comment

by:TSFLLC
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
So you need acording to combobox selection to fill other cells with a certain Value Correct?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:TSFLLC
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
very very welcome....
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

728 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

14 Experts available now in Live!

Get 1:1 Help Now