Tyler King
Tyler King

Reputation: 1

Update SQL data table in c#?

    private void button1_Click(object sender, EventArgs e)       
  {
        string CS = ConfigurationManager.ConnectionStrings["connection_string"].ConnectionString;
        OleDbConnection C = new OleDbConnection(CS);
        C.Open();
        OleDbCommand CMD = new OleDbCommand("", C);
        CMD.CommandText = "SELECT COUNT(*) FROM Applicants WHERE ApplicantID = ?";
        CMD.Parameters.AddWithValue("@ApplicantID", textBox1.Text);
        if (Convert.ToInt32(CMD.ExecuteScalar()) > 0)
        {
            CMD.CommandText = "UPDATE Onboarding SET " +
                "BackgroudCheck = @BGC, PhotoID = @PID, " +
                "TrainingHoursOutOf40 = @THOO, DrugTestTaken = @DTT, PassedDrugTest = @PDT" +
                "WHERE ApplicantID = @AID";
            CMD.Parameters.AddWithValue("@AID", textBox1.Text);
            CMD.Parameters.AddWithValue("@BGC", CheckBox1);
            CMD.Parameters.AddWithValue("@PID", CheckBox2);
            CMD.Parameters.AddWithValue("@THOO", TextBox2.Text);
            CMD.Parameters.AddWithValue("@DTT", CheckBox3);
            CMD.Parameters.AddWithValue("@PDT", CheckBox4);
            MessageBox.Show("Applicant Updated Successfully");
        }
        else
        {
            MessageBox.Show("Applicant Does Not Exists");
        }
        C.Close();
  }

I am trying to update the data table. Some how when I try to update in the form I do get a messagebox saying "Applicant updated Successfully", but when I go to the data table or view it in another form, the table is not updated.

Upvotes: 0

Views: 57

Answers (2)

Caius Jard
Caius Jard

Reputation: 74730

Several problems here

  • Ole does not use named parameters. You can give your parameters names but they're ignored. You must add the right number of parameters in the right order
  • use using to ensure database resources are closed and disposed of when you're done with them
  • You never actually executed your UPDATE query
  • You didn't put .Checked to retrieve the Booleans from your check boxes
  • You don't need to SELECT first. If the update updates no record the applicant doesn't exist. An UPDATE doesn't error if there is nothing to update. ExecuteNonQuery returns an int of how many rows were updated
  • You really should rename your controls after you drop them on the form. Code that is full of Label57, Button29 is effectively obfuscated (meaningless garbage) that is very hard to maintain
  • In c# variables declared inside a method are named with camelCaseLikeThis, not ALLCAPS
  • Be aware that if this is a file based database you're using (it is likely Access if it's ole) that multiple copies of the database file are present on disk. Countless questions are asked "why isn't my db updating" when it is - it's just that the program is updating the db in the bin folder and the dev is looking in the copy of the db in the project folder (which is copied over the top of the bin folder db every time the project is run, which is another reason the program "never remembers anything")
  • if you're using Access, you would do yourself massive favors by switching to an extensively used commercial grade db (sql server Express is free, and SQLite is definitely worth using over Access) and learning entity framework. I appreciate you're on a learning journey but largely what you're learning now isn't widely used in the real world any more, because it's a tedious waste of time somewhat akin to writing your own graphics drivers or Json parsers. If you want to stick with this approach take a look at Dapper, which takes a lot of the pain out of "data access by SQL strings in button click handlers" - opening and closing connections, filling in parameters and types, pulling data out of readers and casting it; all that work can be done by software and dapper can reduce the code you've written here to a single line like c.Execute("UPDATE ...", new { bgcCheckbox.Checked, ... aidTextbox.Text })
  private void button1_Click(object sender, EventArgs e)       
  {
    string cs = ConfigurationManager.ConnectionStrings["connection_string"].ConnectionString;
    using(OleDbConnection c = new OleDbConnection(cs)){
      c.Open();
      using(OleDbCommand cmd = new OleDbCommand("", c)){
       
          cmd.CommandText = "UPDATE Onboarding SET " +
                "BackgroudCheck = ?, PhotoID = ?, " +
                "TrainingHoursOutOf40 = ?, DrugTestTaken = ?, PassedDrugTest = ?" +
                "WHERE ApplicantID = ?";
          
          cmd.Parameters.AddWithValue("@BGC", CheckBox1.Checked);
          cmd.Parameters.AddWithValue("@PID", CheckBox2.Checked);
          cmd.Parameters.AddWithValue("@THOO", TextBox2.Text);
          cmd.Parameters.AddWithValue("@DTT", CheckBox3.Checked);
          cmd.Parameters.AddWithValue("@PDT", CheckBox4.Checked);
          cmd.Parameters.AddWithValue("@AID", textBox1.Text);
          if(cmd.ExecuteNonQuery()>0)
            MessageBox.Show("Applicant Updated Successfully");
          else
            MessageBox.Show("Applicant Does Not Exists");
      }  
    }
  }

Upvotes: 3

Omkar Godse
Omkar Godse

Reputation: 81

You have not used ExecuteNonQuery() method of SQL Command class.

    int returnValue;

    returnValue = CMD.ExecuteNonQuery();

Upvotes: 1

Related Questions