Solved

How do I fill the combobox in a datagridview control?

Posted on 2011-09-28
11
413 Views
Last Modified: 2012-05-12
I have an unbound datagridview control and I am filling the combobox column with the required data using the "MyForm.colDepartment.Items.Add(dr(1))".

colDepartment is the name of my combobox column.

I am filling the combobox column with the text field of the record but I want to be able to access the recordnumber field for the record in my save routine. Is there a way I can assign the recordnumber field to each item in the combo box?
0
Comment
Question by:SheldonC
[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
  • 6
  • 5
11 Comments
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36764257
Hello buddy, the DataGridViewComboBoxColumn class has these properties for that:
DataSource <- To fill your combobox
DisplayMember <- The column of your DataSource that will be used to display values in your combo.
ValueMember <- The column of your DataSource that need to match with DataPropertyName (both must be the same data type)
DataPropertyName <- The column of your DataGridView.DataSource that set the selected item in your combo

Your colDepartment object must be of type DataGridViewComboBoxColumn.

More info:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxcolumn.aspx
0
 

Author Comment

by:SheldonC
ID: 36815614
I am trying to understand the code but I keep getting the following error whenever I fill the form or the mouse moves over the datagrid.

"system.formatexception: DataGridViewComboBoxCell value is not valid"

Attached is my code and routines.
SetAlternateChoicesUsingDataSource(me.colDepartment) 'I call this in the load event of the form

Private Sub SetAlternateChoicesUsingDataSource( _
            ByVal comboboxColumn As DataGridViewComboBoxColumn)

        With comboboxColumn
            .DataPropertyName = ColumnName.Department.ToString()
            .DataSource = RetrieveAlternativeTitles()
            .ValueMember = ColumnName.DeptID.ToString
            .DisplayMember = ColumnName.Department.ToString
        End With

    End Sub

    Private Function RetrieveAlternativeTitles() As DataTable

        Return Populate("SELECT * FROM Department")

    End Function

    Private Function Populate(ByVal sqlCommand As String) As DataTable

        myConnection = New SqlConnection(myconstring)
        myConnection.Open()

        myCommand = New SqlCommand(sqlCommand, myConnection)

        Dim adapter As New SqlDataAdapter()

        adapter.SelectCommand = myCommand

        Dim table As New DataTable()
        table.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter.Fill(table)

        Return table
    End Function
    Enum ColumnName
        DeptID
        Department
    End Enum

Open in new window

0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36815660
With comboboxColumn
    .DataPropertyName = ColumnName.Department.ToString()
    .DataSource = RetrieveAlternativeTitles()
    .ValueMember = ColumnName.DeptID.ToString
    .DisplayMember = ColumnName.Department.ToString
End With

Check this, your DataPropertyName column must be of the same data type that the column of ValueMember.
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

Author Comment

by:SheldonC
ID: 36817813
I did that but I am still getting the same same error. If I set the valuemenber to the same as the displaymember the error goes away but that would defeat the purpose.

What I am trying to achieve is to get the combobox to display the "Department" but return the "DeptID" of the appropriate list item selected.
0
 
LVL 17

Accepted Solution

by:
Carlos Villegas earned 350 total points
ID: 36817972
Hello, I did this example to help you to understand how it work:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim myComboData As New DataTable
    myComboData.Columns.Add("GradeId", GetType(Integer))
    myComboData.Columns.Add("Text", GetType(String))
    myComboData.Rows.Add(1, "A")
    myComboData.Rows.Add(2, "B")
    myComboData.Rows.Add(3, "C")

    Dim myGridData As New DataTable
    myGridData.Columns.Add("StudentId", GetType(Integer))
    myGridData.Columns.Add("Name", GetType(String))
    myGridData.Columns.Add("GradeId", GetType(Integer))
    myGridData.Rows.Add(1, "Jason", 2)
    myGridData.Rows.Add(2, "Mike", 1)
    myGridData.Rows.Add(3, "Joan", 2)
    myGridData.Rows.Add(4, "Roger", 3)

    Dim myGrid As New DataGridView
    myGrid.AutoGenerateColumns = False

    Dim columnA As New DataGridViewColumn()
    columnA.CellTemplate = New DataGridViewTextBoxCell()
    columnA.HeaderText = "Student Name"
    columnA.DataPropertyName = "Name"
    myGrid.Columns.Add(columnA)

    Dim columnB As New DataGridViewComboBoxColumn
    columnB.CellTemplate = New DataGridViewComboBoxCell()
    columnB.HeaderText = "Student Grade"
    columnB.DataPropertyName = "GradeId"
    columnB.DataSource = myComboData
    columnB.ValueMember = "GradeId"
    columnB.DisplayMember = "Text"
    myGrid.Columns.Add(columnB)

    myGrid.DataSource = myGridData

    Me.Controls.Add(myGrid)
End Sub

Open in new window

Copy this to a Form and try it.
0
 

Author Comment

by:SheldonC
ID: 36818049
lol I found the problem. The combobox was filling properly but the problem actually is caused when I populate the datagrid rows. Can you give me an idea of what is the best way to select the appropriate item in the list and how to access the value from the valuemember instead of using what is displayed?
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36818140
Hello:
1. The item in your list is auto selected when it match your data grid view DataSource.
2. When you select an item from the combo it also update your data grid view DataSource.

To get the selected value of your combo, in my example you can use something like this:
If Not myGrid.CurrentCell Is Nothing Then
    Dim gradeId = Convert.ToInt32(CType(myGrid.Rows(myGrid.CurrentCell.RowIndex).DataBoundItem, DataRowView)("GradeId"))
End If

Open in new window

0
 

Author Comment

by:SheldonC
ID: 36818263
I understand how to get the selected value from the cell but where I am having difficulty is selecting the correct item in the list when populating the datagrid
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36818283
But that must be automatic, you need to do nothing, did you test this? #36817972
0
 

Author Closing Comment

by:SheldonC
ID: 36891809
Thanks for the help...solution was excellent!
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 36891823
Glad to help!
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
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…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

688 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