How to programmatically set cell value in DataGridView?

前端 未结 14 888
無奈伤痛
無奈伤痛 2020-11-30 02:05

I have a DataGridView. Some of the cells receive their data from a serial port: I want to shove the data into the cell, and have it update the underlying bound object.

14条回答
  •  旧巷少年郎
    2020-11-30 02:58

    I came across the same problem and solved it as following for VB.NET. It's the .NET Framework so you should be possible to adapt. Wanted to compare my solution and now I see that nobody seems to solve it my way.

    Make a field declaration.

    Private _currentDataView as DataView

    So looping through all the rows and searching for a cell containing a value that I know is next to the cell I want to change works for me.

    Public Sub SetCellValue(ByVal value As String)
        Dim dataView As DataView = _currentDataView
    
        For i As Integer = 0 To dataView.Count - 1
            If dataView(i).Row.Item("projID").ToString.Equals("139") Then
                dataView(i).Row.Item("Comment") = value
                Exit For ' Exit early to save performance
            End If
        Next
    End Sub
    

    So that you can better understand it. I know that ColumnName "projID" is 139. I loop until I find it and then I can change the value of "ColumnNameofCell" in my case "Comment". I use this for comments added on runtime.

提交回复
热议问题