Solved

How do I fill the combobox in a datagridview control?

Posted on 2011-09-28
11
392 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Multiple file Upload asp.net 2 49
vb.net help 4 31
start a process from a service 3 23
export data table to excel in vb.net 10 27
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

809 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