Home > Mobile >  how to implement update button for datagridview and save values to database using a dataHandler clas
how to implement update button for datagridview and save values to database using a dataHandler clas

Time:11-04

good day, hope everyone is well :)

I'm a first year student, and we just started with windows forms. I want to update data from DataGridview into my database using a button but I have to create an update method in a data handler class and call it in my form load, this is what I have tried so far.

DataHandler class:

        public void UpdateStudent(int number, string name, string surname, string dob, string gender, int phone, string address)
    {
        try
        {
            //string updateQuery = @"UPDATE Student SET number='"   number   "'name='"   name   "'surname='"   surname   "'dob='"   dob   "'gender'"   gender   "'phone='"   phone   "'address='"   address   "'";
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.ExecuteNonQuery();
            MessageBox.Show("updated successfully....");
        }
        catch (Exception ex)
        {
            MessageBox.Show("not updated!", ex.Message); m
        }
        finally
        {
            conn.Close();
        }
    }

update button on form load:

  DataHandler dh = new DataHandler();

 dh.UpdateStudent(int.Parse(txtStuID.Text), txtStuName.Text, txtStuSurname.Text,txtStuDOB.Text,txtStuGender.Text, int.Parse(txtStuNo.Text), txtStuAddress.Text);
       

CodePudding user response:

This is how you need to initialize SqlCommand:

new SqlCommand(queryString, connection);

You have missed passing any parameters. You will need to pass updateQuery as queryString and you will also need a proper connection string.

CodePudding user response:

I think the actual issues that brought you here are a couple of key issues with your SQL being invalid. However, with that having been said, the comments regarding SQL injection are absolutely correct, and you would do well to learn about parameterized SQL.

First thing that jumps out is that your parameters need to be comma separated for this to be valid SQL. The second thing is that you need to be identifying the row you wish to update with a WHERE clause, your current SQL statement is going to update every record in your table, not a single record. Basically, your "number" field should not be in the list of columns to be updated, it needs to be moved to your WHERE clause.

Below is not a full solution to your homework assignment, but a snippet of the SQL with the issues corrected. One thing you can do to help yourself as you learn is to try to get your SQL to compile and run outside of your program, and then implement it in your program once you have a working statement.

UPDATE Student SET name = 'John', surname = 'Doe' WHERE number = 1

  • Related