Adding items to a combobox in DataGridView

瘦欲@ 提交于 2020-01-06 19:34:50

问题


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.


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/5311178/adding-items-to-a-combobox-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!