Solved

How do I fill the combobox in a datagridview control?

Posted on 2011-09-28
11
383 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

895 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

17 Experts available now in Live!

Get 1:1 Help Now