是否可以在函式中創建 DataGridViewRow,獨立于控制元件,然后通過呼叫程序將其添加到任意控制元件?還是必須與控制元件關聯創建行,然后根據需要進行操作?
我正在創建一個帶有多個 DataGridView 控制元件的 VB.Net 表單。它們都具有相似的目的,具有相同的列編號和名稱。我想在函式中獨立創建行和單元格,然后在函式回傳后將它們添加到正確的控制元件中。
這是我正在嘗試做的一個簡化示例。這不起作用。我收到錯誤'New' cannot be used on a class that is declared 'MustInherit',但找不到解決方案。
Private Sub frmDataGridViewCellTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.Columns.Add("colA", "A")
DataGridView1.Columns.Add("colB", "B")
DataGridView1.Columns.Add("colC", "C")
Dim r As DataGridViewRow = CreateRow()
DataGridView1.Rows.Add(r)
End Sub
Private Function CreateRow() As DataGridViewRow
Dim r As New DataGridViewRow 'Create a new row independently of any DataGridView control.
Dim i As Integer
i = r.Cells.Add(New DataGridViewCell) 'error here
r.Cells.Item(i).Value = "Hello"
i = r.Cells.Add(New DataGridViewCell) '...and here
r.Cells.Item(i).Value = "world"
i = r.Cells.Add(New DataGridViewCell) '...and here
r.Cells.Item(i).Value = "!"
Return r
End Function
uj5u.com熱心網友回復:
ADataGridView不包含香草DataGridViewCell物件。每個單元格都是繼承的特定型別DataGridViewCell。當您通過網格本身添加一行時,將根據列生成單元格,例如為 a 生成的單元格DataGridViewTextBoxColumn將是 a DataGridViewTextBoxCell。這是默認的列型別,所以這就是您的列,所以這就是您制作單元格所需要的。
uj5u.com熱心網友回復:
創建新的DataGridViewRow時,還需要先對其進行初始化,DataGridViewCellCollection然后才能添加它們的值。DataGridViewColumn.CellTemplate根據每個屬性中定義的型別創建和初始化單元格DataGridViewColumn。為此,創建一個新行,然后呼叫CreateCells需要DataGridView引數的方法來獲取提到的每個單元格的模板。
CreateRow因此,您可以按如下方式重構該函式:
Private Function CreateRow(dgv As DataGridView) As DataGridViewRow
Dim row = New DataGridViewRow
row.CreateCells(dgv, "Hello", "World", "!")
Return row
End Function
' And maybe
Private Function CreateRow(dgv As DataGridView,
value1 As String,
value2 As String,
value3 As String) As DataGridViewRow
Dim row = New DataGridViewRow
row.CreateCells(dgv, value1, value2, value3)
Return row
End Function
呼叫者,召集者:
Dim newRow = CreateRow(DataGridView1)
DataGridView1.Rows.Add(newRow)
'Or
Dim newRow = CreateRow(DataGridView1, "Hello", "Word", "!")
DataGridView1.Rows.Add(newRow)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/455657.html
