使用Windows窗体。以下是DataGridView.AutoGenerateColumns Property中的示例。我试图弄清楚如何使用AutoGenerateColumns = False添加自定义列。
Private Sub Form_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SetBinding3()
End Sub
Private Class Employee
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _Name As String
End Class
Private employees As New List(Of Employee)
Dim bs As New BindingSource
Private Sub SetBinding3()
employees.Add(New Employee With {.Name = "Henry"})
employees.Add(New Employee With {.Name = "Mary"})
dgBilling.AutoGenerateColumns = False
bs.DataSource = employees
dgBilling.DataSource = bs
Dim col2 As New DataGridViewTextBoxColumn
col2.HeaderText = "Name"
col2.Name = "Name"
col2.ValueType = GetType(String)
col2.DataPropertyName = "Name"
col2.Width = 500
col2.DefaultCellStyle.ForeColor = Color.Black
col2.DefaultCellStyle.BackColor = Color.Beige
dgBilling.Columns.Add(col2)
dgBilling.Refresh()
End Sub
除了我在DataGridView中看不到数据外,其他一切似乎都正常工作。如果单击它,名称将被选中并可见。但是,如果我没有选择,那么它是不可见的。我尝试将ForeColor和BackColor设置为无效。如何正确添加AutoGenerateColumns = False的列?
答案 0 :(得分:1)
也许有一种更简单的方法,但是我已经成功地做到了。请注意,我有使用List(Of T)而不是BindingSource绑定到DataGridView的自定义类。字符串columns
是对象的属性名称和列的标题文本的配对。即“名称”为Product.Name
,“产品编号”是DataGridView列标题中显示的内容。
dgvItemList.AutoGenerateColumns = False
dgvItemList.DataSource = Services.MasterLists.Products.GetList
Dim columns As String() = {"ID", "ID",
"Name", "Product #",
"Description", "Description",
"Family", "Family",
"Comments", "Comments"}
Helpers.Controls.AddColumnsToDataGridView(dgvItemList, columns)
dgvItemList.Columns(0).Visible = False
dgvItemList.Columns(1).Width = 90
dgvItemList.Columns(2).Width = 200
dgvItemList.Columns(3).Width = 100
dgvItemList.Columns(4).Width = 200
以及Helpers.Controls.AddColumnsToDataGridView的定义:
Public Shared Sub AddColumnsToDataGridView(ByRef dgv As DataGridView, ByVal columns As String())
dgv.Columns.Clear()
For i As Integer = 0 To columns.Length - 1 Step 2
Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
' i = index of the object's property name. i + 1 = the column name to show in the grid
column.DataPropertyName = columns(i)
column.Name = columns(i + 1)
dgv.Columns.Add(column)
Next
End Sub
之所以这样做,是因为我不希望DataGridView显示Product
对象的所有属性,而只显示我想要显示的字段。
答案 1 :(得分:0)
结果是我在RowPrePaint处理程序中出错。它引用的是不存在的列。由于该错误,未呈现行。
Private Sub dgv_RowPrePaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles dgv.RowPrePaint
dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = dgv.Rows(e.RowIndex).Cells("RowColor").Value
End Sub
一旦我纠正了错误,一切都很好!