Jimmy
Jimmy

Reputation: 2106

Adding items to a combobox in DataGridView

I've a DataGridView in a winforms app. Apart from the 4 columns coming from the db table,I need to show an additional column having a combobox in the datagridview[may be using DataGridViewComboColumn?]. 2.And then I want to add different set of items to each combobox for every row.

How do I go about this?

Thanks.

Upvotes: 0

Views: 8128

Answers (2)

Ted
Ted

Reputation: 755

I was looking for an answer to this in VB.NET, but found the C# answer here.

In VB you can do:

Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete

    For Each row As DataGridViewRow in DataGridView1.Rows
        If TypeOf row.Cells(0) Is DataGridViewComboBoxCell AndAlso row.Index = 1 Then
            TryCast(row.Cells(0), DataGridViewComboBoxCell).Items.Add("A")
        Else
            TryCast(row.Cells(0), DataGridViewComboBoxCell).Items.Add("B")
        End If
    Next

End Sub

To Edit:

TryCast(row.Cells(0), DataGridViewComboBoxCell).Value = TryCast(row.Cells(0), DataGridViewComboBoxCell).Items(0)

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38200

You may try to add them via DataBindingComplete of the grid

Something on these lines

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
       if (row.Cells[0] is DataGridViewComboBoxCell && row.Index == 1)
          (row.Cells[0] as DataGridViewComboBoxCell).Items.Add("A");
       else
          (row.Cells[0] as DataGridViewComboBoxCell).Items.Add("B");
    }
}

Hope this helps EDIT

(row.Cells[0] as DataGridViewComboBoxCell).Value = (row.Cells[0] as DataGridViewComboBoxCell).Items[0];

When that cell is selected then the first value would be shown selected

Upvotes: 2

Related Questions