我有一些数据表。我遍历了我拥有的数据表的数量。在循环中,我创建了一个DataGridView,数据源是该索引处的给定数据表。我怎样才能将列更改为Combobox类型?我知道如何在设计师身上做到这一点但是以编程方式呢?我试过了:
For each column as DataGridViewColumn in table.Columns
column.CellType = DataGridViewComboBoxColumn
Next
显然这不起作用。 CellType是一个只读属性,我不能简单地将它设置为类类型。我知道这可能很简单,我知道我很愚蠢。请帮忙。
答案 0 :(得分:0)
您无需将整个列定义为组合框。请参阅我的示例,其中您对每个行具有相同值的组合框的定义。我还为您提供了一种只用组合框替换单个单元格的方法。看看“people”列是一个文本框列,我在其中放置了一个组合框。它还向您展示如何分配值和设置默认值。这与复选框列/单元格的概念相同。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim NewCol As New DataGridViewComboBoxColumn
DataGridView1.Columns.Add(New DataGridViewTextBoxColumn With {.Name = "ID", .HeaderText = "ID"})
With NewCol
.Name = "ComboBoxCol"
.HeaderText = "Language"
.Items.Add("VB.NET")
.Items.Add("C#")
.Items.Add("F#")
.DefaultCellStyle.NullValue = .Items(0)
End With
DataGridView1.Columns.Add(NewCol)
DataGridView1.Columns.Add(New DataGridViewTextBoxColumn With {.Name = "PeopleCol", .HeaderText = "People"})
Dim xRow As String() = {"1"}
DataGridView1.Rows.Add(xRow)
DataGridView1.Rows.Add({"2"})
DataGridView1(1, 0).Value = "C#"
Dim xPeople1 As New DataGridViewComboBoxCell
With xPeople1
.Items.Add("Santa")
.Items.Add("Satan")
.Value = .Items(0)
End With
DataGridView1(2, 0) = xPeople1
Dim xPeople2 As New DataGridViewComboBoxCell
With xPeople2
.Items.Add("God")
.Items.Add("Allah")
.Value = .Items(1)
End With
DataGridView1(2, 1) = xPeople2
End Sub
End Class