Results 1 to 6 of 6

Thread: WIndows form Add new record with code

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Location
    Oklahoma, USA
    Posts
    92

    WIndows form Add new record with code

    I have a form that everything works on except adding records when called from another form. I am trying to add with the bindingsource.addnew. Which I like because it doesn't save until they hit the save button. This is what I have but I read it doesn't work. The bindingsource addnew only creates a detached record so this wont work.

    Code:
            If Application.OpenForms().OfType(Of OperShiftLog).Any _
            Or Application.OpenForms().OfType(Of OperShiftLog1).Any Then
                Me.Laser_Status_InfoBindingSource.Filter = "Printer = '" & Pass_Printer & "'"
                If Pass_AddMod = "M" Then
                    BindingNavigatorDeleteItem.Enabled = False
                    BindingNavigatorAddNewItem.Enabled = False
                    Me.Laser_Status_InfoBindingSource.Filter = "Shift_FKey = '" & Pass_Shift_Key & "' AND Printer = '" & Pass_Printer & "'"
                Else
                    Add_New = True
                    Me.Laser_Status_InfoBindingSource.AddNew()
                    tbStatus_key.Text = Int32.MaxValue
                    tbShift_FKey.Text = Pass_Shift_Key
                    chkbSerReq.Checked = False
                    tbSvcReq.Text = ""
                    tbMeter.Text = 0
                    cmbStatus.Text = "Up"
                    dtpErr_time.Value = DateTime.Now
                    cmbPrinter.SelectedValue = Pass_Printer
                    cmbOperator.SelectedValue = Pass_Operator
                    cmbStatus.Focus()
                    'Save_Current()
                End If
                cmbSelPrinter.Visible = False
                '.visible = False
                chkbActiveSel.Visible = False
                'cmbSelPrinter.SelectedValue = Pass_Printer
                'cmbSelPrinter.Enabled = False
                'chkbActiveSel.Enabled = False
                cmbPrinter.Enabled = False
                cmbOperator.Enabled = False
                dgvLaser_Status_Info.Enabled = False
            Else
                Me.Laser_Status_InfoBindingSource.Filter = "Printer = '" & cmbSelPrinter.SelectedValue & "'"
                Me.Laser_Status_InfoBindingSource.Sort = "Err_Time"
                Me.Laser_Status_InfoBindingSource.MoveLast()
    
                chkbActiveSel.Checked = True
                fillSelPrinter()
            End If

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: WIndows form Add new record with code

    Quote Originally Posted by wjburke2 View Post
    The bindingsource addnew only creates a detached record
    With a DataTable bound to a BindingSource, calling AddNew on the BindingSource is equivalent to calling NewRow on the DataTable. The new DataRow has to be Detatched by default because it contains no data by default, so it might violate various constraints. Once the fields of the DataRow have been populated appropriately, you need to call Rows.Add on the DataTable to add the DataRow and set its RowState to Added. The equivalent of that using the BindingSource is calling EndEdit.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Location
    Oklahoma, USA
    Posts
    92

    Re: WIndows form Add new record with code

    Thank you, That makes the why clearer. After the user has complete their changes standard save code is used to update. It has a bindingsource.endEdit. I have traced the code to a check for dataset.haschanges statement in the Dataset.designer.vb the check returns False and the update fails.
    The bindingsource.current row has the new record with changes. But when I look at the Datasource with the Dataset visualizer it is not added. So am I missing something to add/attach the row.
    One more observation, I can add a record using the BindingNavagator.AddItem button. the only difference is I don't have the recordId and prefilled data from the calling form.

    Code:
        Private Sub Laser_Status_InfoBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) _
            Handles Laser_Status_InfoBindingNavigatorSaveItem.Click, btnSave.Click
    
            Me.Validate()
            Me.Laser_Status_InfoBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.LaserMaintLogDataSet)
    
            If LaserMaintLogDataSet.HasErrors Then
                MsgBox("Record Not Saved")
            Else
                MsgBox("Record Saved")
            End If
    
        End Sub
    Code:
            Public Overridable Function UpdateAll(ByVal dataSet As LaserMaintLogDataSet) As Integer
                If (dataSet Is Nothing) Then
                    Throw New Global.System.ArgumentNullException("dataSet")
                End If
                If (dataSet.HasChanges = false) Then
                    Return 0
                End If
    Last edited by wjburke2; Jun 25th, 2020 at 10:41 PM.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: WIndows form Add new record with code

    It's hard to say for sure what the issue is based on the information you have provided but I would guess that you actually have two different LaserMaintLogDataSet objects and you are adding the new row to one of them and then trying to save changes from the other. Did you add DataSets to both forms in the designer? If so then they are two different objects.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Oct 2009
    Location
    Oklahoma, USA
    Posts
    92

    Re: WIndows form Add new record with code

    I am not sure either. I did get it to work after thinking about what you said and reevaluating the code. I was updating the controls on the Form thinking that would update the binding source. That assumption was wrong as most of the controls binding are set to "Datasource Update Mode: OnValidation". so setting them in code bypasses the validation therefore the bindingsource was no updated. The solution I came up with is to update the Bindingsource directly. Then call the endedit, This worked and the new record was added to the datasource with default values. I need to clean up the code but it worked. Thanks

    Code:
        Private Sub PrtProblemLog1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            First_Time = True
    
            Me.OperatorsTableAdapter.Fill(Me.LaserMaintLogDataSet.Operators)
            Me.PrintersTableAdapter.Fill(Me.LaserMaintLogDataSet.Printers)
            Me.Laser_Status_InfoTableAdapter.Fill(Me.LaserMaintLogDataSet.Laser_Status_Info)
    
            currUser = UserManager.GetCurrentUser()
            lblUserName.Text = currUser.Name
    
            If Application.OpenForms().OfType(Of OperShiftLog).Any _
            Or Application.OpenForms().OfType(Of OperShiftLog1).Any Then
                Me.Laser_Status_InfoBindingSource.Filter = "Printer = '" & Pass_Printer & "'"
                If Pass_AddMod = "M" Then
                    BindingNavigatorDeleteItem.Enabled = False
                    BindingNavigatorAddNewItem.Enabled = False
                    Me.Laser_Status_InfoBindingSource.Filter = "Shift_FKey = '" & Pass_Shift_Key & "' AND Printer = '" & Pass_Printer & "'"
                Else
                    Me.Laser_Status_InfoBindingSource.Filter = "Printer = '" & Pass_Printer & "'"
                End If
            Else
                Me.Laser_Status_InfoBindingSource.Filter = "Printer = '" & cmbSelPrinter.SelectedValue & "'"
                Me.Laser_Status_InfoBindingSource.Sort = "Err_Time"
                Me.Laser_Status_InfoBindingSource.MoveLast()
    
                chkbActiveSel.Checked = True
                fillSelPrinter()
            End If
    
            First_Time = False
        End Sub
        Private Sub PrtProblemLog1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    
            If Pass_AddMod = "A" Then
                Add_New = True
                Me.Laser_Status_InfoBindingSource.AddNew()
                'tbStatus_key.Text = Int32.MaxValue
                Me.Laser_Status_InfoBindingSource.Current("Shift_FKey") = Pass_Shift_Key
                Me.Laser_Status_InfoBindingSource.Current("Printer") = Pass_Printer
                Me.Laser_Status_InfoBindingSource.Current("Operator") = Pass_Operator
                Me.Laser_Status_InfoBindingSource.Current("Status") = "Up"
                Me.Laser_Status_InfoBindingSource.Current("Meter") = 0
                Me.Laser_Status_InfoBindingSource.Current("Err_Time") = DateTime.Now
                Me.Laser_Status_InfoBindingSource.Current("Problem") = ""
                Me.Laser_Status_InfoBindingSource.EndEdit()
    
                cmbStatus.Focus()
                chkbSerReq.Checked = False
                cmbSelPrinter.Visible = False
                chkbActiveSel.Visible = False
                cmbPrinter.Enabled = False
                cmbOperator.Enabled = False
                dgvLaser_Status_Info.Enabled = False
            End If
    
        End Sub

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: WIndows form Add new record with code

    Quote Originally Posted by wjburke2 View Post
    That assumption was wrong as most of the controls binding are set to "Datasource Update Mode: OnValidation". so setting them in code bypasses the validation therefore the bindingsource was no updated.
    A workaround for that is to call ValidateChildren on the form. Your original code called Validate, which will validate the last control to have focus. ValidateChildren will validate every control on the form.
    Quote Originally Posted by wjburke2 View Post
    The solution I came up with is to update the Bindingsource directly. Then call the endedit
    You should be using the BindingSource in code anyway. That's what it's for: access to the bound data in code. The controls are for the user.

    That said, you're not really updating the BindingSource. You would use the BindingSource to get the current data-bound item, which would be a DataRowView, and update that. If you want to work with a DataRow instead of a DataRowView then you can get that from its Row property. If you're using a typed DataTable, you can cast that DataRow as your typed DataRow type, e.g.
    vb.net Code:
    1. Dim rowView = DirectCast(Laser_Status_InfoBindingSource.Current, DataRowView)
    2. Dim row = DirectCast(rowView.Row, Laser_Status_InfoDataRow)
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width