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.
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
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)
精彩评论