几个月前我在网上找到了这段代码。它非常适合创建datagridview列。我从来没有用它来创建一个组合柱。现在我需要这样做,并且无法弄清楚如何为列分配值。而且,我找不到我第一次找到这段代码的地方。我现在可以找到它的片段但没有完整的。
创建文本框并创建包含值的dgv行很容易。但是,我不知道如何创建一个组合柱。顺便说一下,在这种情况下,列可以为每一行使用相同的组合框值。
这是我的代码:
我创建一个数据表来保存要绑定到dgv的数据:
Dim dt As New DataTable("Grid")
Dim dr As DataRow
dtSetupColumns(dt)
Public Sub dtSetupColumns(ByRef dt As DataTable)
dt.Columns.Add("name_l", GetType(String))
dt.Columns.Add("name_f", GetType(String))
dt.Columns.Add("state", GetType(String))
End Sub
为数据表分配值:
dr = dt.NewRow()
dr("name_l") = ' from query table
dt.Rows.Add(dr)
创建DataGridView列:
dgvCreateColumns(dgv)
Public Sub dgvCreateColumns(ByRef inDataGridView As DataGridView)
With inDataGridView.Columns
.Add(dgvCreateColumn(ColumnStyle.TextBoxColumn, String.Empty, "Last Name", "name_l", 80, DataGridViewContentAlignment.MiddleLeft))
.Add(dgvCreateColumn(ColumnStyle.TextBoxColumn, String.Empty, "First Name", "name_f", 80, DataGridViewContentAlignment.MiddleLeft))
.Add(dgvCreateColumn(ColumnStyle.ComboBoxColumn, String.Empty, "State", "state", 80, DataGridViewContentAlignment.MiddleLeft))
End With
End Sub
Public Shared Function dgvCreateColumn(ByVal ColumnType As ColumnStyle, ByVal format As String, ByVal headerText As String, ByVal dataPropertyName As String, ByVal width As Integer, ByVal alignment As DataGridViewContentAlignment, Optional ByVal bMakeVisible As Boolean = True, Optional ByVal inReadOnly As Boolean = False) As DataGridViewColumn
Dim dgvC As DataGridViewColumn = Nothing
Select Case ColumnType
Case ColumnStyle.ButtonColumn
dgvC = New DataGridViewButtonColumn
Case ColumnStyle.CheckBoxColumn
dgvC = New DataGridViewCheckBoxColumn
Case ColumnStyle.ComboBoxColumn
dgvC = New DataGridViewComboBoxColumn
Case ColumnStyle.ImageColumn
dgvC = New DataGridViewImageColumn
Case ColumnStyle.LinkColumn
dgvC = New DataGridViewLinkColumn
Case ColumnStyle.TextBoxColumn
dgvC = New DataGridViewTextBoxColumn
End Select
With dgvC
.DataPropertyName = dataPropertyName
.DefaultCellStyle.Alignment = alignment
.DefaultCellStyle.Format = format
If ColumnType = ColumnStyle.ButtonColumn Then
'.colum()
End If
.HeaderText = headerText
.Name = headerText
.ReadOnly = inReadOnly
If width = 0 Then
.Visible = False
Else
.Width = width
If bMakeVisible = False Then
.Visible = False
Else
.Visible = True
End If
End If
End With
Return dgvC
End Function
答案 0 :(得分:0)
你必须通过每一行中的每个细胞
For i as Integer = 0 to dgv.Rows.Count -1
Dim gridComboBox As New DataGridViewComboBoxCell
gridComboBox.DataSource = dt
gridComboBox.ValueMember = dt.Columns(0).ColumnName
dgv.Item(2, i) = gridComboBox 'Change the Cell in Column:2 Row:i to ComboBox
Next