4d4c
4d4c

Reputation: 8169

DataGridViewComboBoxColumn in DataGridView

I'm writing a small application to view and edit mySQL tables.

I want to put ComboBox input inside the DataGridView, to choose data from foreign key in other table.

Is the any method to do so?

So far I have only found this code:

        Dim cmb As New DataGridViewComboBoxColumn()
        cmb.HeaderText = "Select Data"
        cmb.Name = "cmb"
        cmb.DataSource = Form1.table
        cmb.DisplayMember = "adrese_id"
        cmb.ValueMember = "adrese_id"
        cmb.DataPropertyName = "adrese_id"
        DataGridView1.Columns.Add(cmb)

        Form1.adapter.Update(Form1.table)  

This is my tables:

abonenti

abonents_id PK
vards
uzvards
tel_num
adrese_id FK

adreses

adrese_id PK
dziv_num
iela

When I select something from the comboBox it will just return to the value that is in the table. So I can't change it to any other.

Does somebody knows how to fix that, or how to make a comboBox working with foreign key inside the data grid view?

P.S. Also is there a way to place that select column instead the original?

Thanks.

Upvotes: 1

Views: 886

Answers (1)

WozzeC
WozzeC

Reputation: 2660

This is what I came up with when I did something similar.

After inserting data into the datagridview you convert the cell to a combobox. So basically you loop through the DGV like the code below and change the cell type. You set the dgvDropDown items to be the items from the database (as strings of course). Just remember that if the value of the item isn't found in the drop down then an error will occur.

int column = 0     
For row As Integer = 0 To DataGridView1.Rows.Count - 1
        Dim dgvDropDown As DataGridViewComboBoxCell = New DataGridViewComboBoxCell()
        dgvDropDown.Items.Add("dbItem1")
        dgvDropDown.Items.Add("dbItem2")
        DataGridView1.Item(column, row) = dgvDropDown
Next

Upvotes: 1

Related Questions