Datagridview combobox column unique value each row

Malik Asad Mahmood 126 Reputation points
2020-12-09T18:13:34.503+00:00

Hi,
Please I am using winform vb.net I have datagridview which contain combobox column and I want to assign unique values to combobox column of each row, It could be 3 to 4 values and these values I am already getting from database as out parameters and please help me how I can achieve this
thank you.
regards,
asad

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,644 questions
{count} votes

Accepted answer
  1. Albert Kallal 5,226 Reputation points
    2020-12-10T11:28:56.527+00:00

    We need a wee bit more information.

    However, assuming in the form load, I load up a grid with this:

     Dim rst As DataTable = MyRst("SELECT FirstName, LastName, City FROM Customers")  
          
    DataGridView1.DataSource = rst  
      
      
    

    And thus we get this for a grid:

    46859-image.png

    Now, it obvious if we have a combo box in a grid, and we want to filter? Then we talking about a cascading combo.

    In above, obviously the combo is to ONLY show hotels from the given city.

    So, in the row enter event we can do this:

            If DataGridView1.Rows.Count <= 0 Then Exit Sub  
      
            Dim Grow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)  
            Dim Mycombo As DataGridViewComboBoxCell  
            Mycombo = Grow.Cells.Item("FavorateHotel")  
      
            Dim sCity As String = Grow.Cells.Item("City").Value  
      
            Dim strSQL As String = "SELECT HotelName from tblHotels where City = '" & sCity & "'"  
      
            Dim r As DataTable = MyRst(strSQL)  
            Mycombo.Items.Clear()  
            For Each dr As DataRow In r.Rows  
                Mycombo.Items.Add(dr("HotelName"))  
            Next  
      
    

    Now, to be fair - I would suggest using a dataView item that you can filter - but if the "list" of choices is small, then the above is rather fine. But it does mean if a user were to say hold a down arrow key, we would be firing off a new query for every row. So, I used the above row event, but we should in fact use a cell click event.

    But , the above is a starting point, and you can work from the above code concepts. They are that for each row, you have to setup the combo box source.

    I do believe that the data source persits - so we could (should) check if the combo box already has been given a set of values - thus no need to re-load for each row.

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada

    0 comments No comments

0 additional answers

Sort by: Most helpful