Tuesday, October 21, 2014

Datagridview add a row from programming code

I cannot add a row directly to datagridview if it is databound

Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound



If I do not use binding navigator to add a row, below code can replace to manual key in "+" with data



 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim icnt As Integer = OutputLineDataGridView.Rows.Count

        Dim newRow As DataRow = _CPC_CPX_MappingDataSet.Tables(0).NewRow
        newRow("CPCCode") = "cpccode 123"
        newRow("CPCDesc") = "cpc desc"
        newRow("CPXRule") = "cpc rule"
        _CPC_CPX_MappingDataSet.Tables(0).Rows.Add(newRow)
        Me.Validate()
        Me.OutputLineBindingSource.EndEdit()
        Try
            Me.TableAdapterManager.UpdateAll(Me._CPC_CPX_MappingDataSet)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
        Me.OutputLineTableAdapter.Fill(Me._CPC_CPX_MappingDataSet.OutputLine)
        ' OutputLineDataGridView.Rows.Add("1", "2", "3")
        'openDatabase()
        'Dim Command As OleDbCommand
        'Dim icount As Integer
        ''ListBox1.Items.Add(txtOutPutCPXRule.Text)
        ''txtOutPutCPXRule.Text = String.Empty
        'Dim sSQL As String
        'sSQL = "INSERT INTO OUTPUTLINE (CPCCode,CPCDesc,CPXRule) VALUES('" & "A0123" & "','" & "Test desc" & "','" & _
        '   "testcpx rule" & "')"
        'Try
        '    Command = New OleDbCommand(sSQL, connection)
        '    icount = Command.ExecuteNonQuery
        'Catch ex As Exception
        '    MessageBox.Show("could not insert record with err:" & ex.Message)
        'End Try
        'Me.OutputLineTableAdapter.Fill(Me._CPC_CPX_MappingDataSet.OutputLine)
        'OutputLineDataGridView.Refresh()
    End Sub

No comments:

Post a Comment