代码之家  ›  专栏  ›  技术社区  ›  spinjector

添加到DataGridView控件的新行的列是否可以按名称引用。。?

  •  0
  • spinjector  · 技术社区  · 7 年前

    我正在Visual Studio 2008中创建Windows Forms 2.0应用程序。表单有一个DataGridView控件,该控件将通过重载以编程方式向其添加行 Add(ByVal ParamArray Values()) ,如图所示:

    dgv.Rows.Add (var1, var2, var3, varEtc)
    

    有没有办法提到细胞 按姓名 而不是依靠他们的 顺序 .. ?

    dgv将有许多列,在我开发应用程序时,按顺序引用它们会让人困惑。通过一些名称或索引字符串来引用它们会容易得多。

    不幸的是,DataGridView类太多太多,我不知道该往哪个方向发展。我有一个不成熟的想法,首先创建每个行对象,配置它,然后将其添加到集合中,如下所示:

    Dim dgvr as DataGridViewRow = New DataGridViewRow
    ...more code needed...
    dgvr.SomeProp.ID    = var1
    dgvr.SomeProp.NameF = var2
    dgvr.SomeProp.NameL = var3
    dgvr.SomeProp.Etc   = varEtc
    dgv.Rows.Add (dgvr)
    

    我相信这不是唯一的方法,甚至还不是实用的方法。我能做到吗。。 ? 还有什么其他的方法。。 ? 还有更好的吗。。 ?

    0 回复  |  直到 7 年前
        1
  •  0
  •   spinjector    7 年前

    这个 link 在Mick on的评论中 我的行动让我走上了我所希望的道路——这比我最初设想的要多出几步。

    我最终得到的是一个 DataGridViewRow .它在新的扩展功能中添加了一个 GetCellByColumnCaption ,它正是这样做的:它返回一个 DataGridViewCell 对象,该对象对应于 DataGridView 控制

    这样做可以避免控件名成为问题。现在,我可以简单地通过新行中最可见的标识符来引用单元格:列标题文本。

    下面是一个有效的例子。。。

    Public Class Form1
    
        Private Sub Form1_Load( _
                            ByVal sender As Object, _
                            ByVal e As System.EventArgs _
                            ) _
                            Handles Me.Load
    
            'Remove the new blank row.
            dgv.AllowUserToAddRows = False
    
        End Sub
    
        Private Sub Button1_Click( _
                            ByVal sender As System.Object, _
                            ByVal e As System.EventArgs _
                            ) _
                            Handles Button1.Click
    
            Dim newRowIdx As Integer = dgv.Rows.Add()
            Dim newRowObj As DataGridViewRow = dgv.Rows.Item(newRowIdx)
            newRowObj.GetCellByColumnCaption("ID").Value = "123"
            newRowObj.GetCellByColumnCaption("Name").Value = "Bob"
            newRowObj.GetCellByColumnCaption("Etc").Value = "Red"
    
        End Sub
    
    End Class
    
    Module ClassExtensions
        'Note: The Extension() attribute requires .Net 3.5 or above. 
        <System.Runtime.CompilerServices.Extension()> _
        Friend Function GetCellByColumnCaption( _
                            ByVal dgvr As DataGridViewRow, _
                            ByVal colCaption As String _
                            ) _
                            As DataGridViewCell
    
            For Each cell As DataGridViewCell In dgvr.Cells
                Dim hdrText = LCase(cell.OwningColumn.HeaderText)
                colCaption = LCase(colCaption)
                If hdrText = colCaption Then
                    GetCellByColumnCaption = cell
                    Exit Function
                End If
            Next
            GetCellByColumnCaption = Nothing
        End Function
    
    End Module