Search code examples
c#linqdatagridviewupdating

Updating data into Database


I have problems adding data into the database. The code that I have written could only update the shiftTiming_Start but not the shiftTiming_Stop. Can someone please help take a look at my code and see what went wrong. Thanks a lot.

private void btnUpdate_Click(object sender, EventArgs e) {
  using (testEntities Setupctx = new testEntities()) {
    var toBeUpdated = txtStart.Text;
    var toBeUpdated1 = txtStop.Text;
    shifthour updateShift = new shifthour();
    updateShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdated);
    updateShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdated1);
    updateShift.shiftTiming_start = txtStart.Text;
    updateShift.shiftTiming_stop = txtStop.Text;
    Setupctx.SaveChanges();
    txtStart.Text = "";
    txtStop.Text = "";
    MessageBox.Show("Shift Timing Has Been Updated.");
  }
}

Solution

  • Assuming I'm following you correctly (I would recommend using more meaningful variable names), update the code as follows:

    private void btnUpdate_Click(object sender, EventArgs e) {
      using (testEntities Setupctx = new testEntities()) {
        var toBeUpdatedStart = txtStart.Text;
        var toBeUpdatedStop = txtStop.Text;
        shifthour updateStartShift;
        shifthour updateStopShift;
        updateStartShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdatedStart);
        updateStopShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdatedStop);
        if (updateStartShift != null)
        {
           updateStartShift.shiftTiming_start = txtStart.Text;
        }
        if (updateStopShift != null)
        {
            updateStopShift.shiftTiming_stop = txtStop.Text;
        }
        Setupctx.SaveChanges();
        txtStart.Text = "";
        txtStop.Text = "";
        MessageBox.Show("Shift Timing Has Been Updated.");
      }
    }