Solved

How do I fill the combobox in a datagridview control?

Posted on 2011-09-28
11
368 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
  • 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
 

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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
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…

757 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

22 Experts available now in Live!

Get 1:1 Help Now