简体   繁体   中英

SQL Server database is not updating C#

I'm new to database programming and C#. I'm using SQL server database and connected it to my winforms application. Everything is fine, i can add new rows, and read information from the database but when i try to edit values, it does not seem to work.

Here is the code i'm using.

         private void btneUpdate_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"
                Data Source = localhost; 
                Initial Catalog = BookStore; 
                Integrated Security = True;");
            SqlCommand cmd;               

            if(MessageBox.Show("You are about to save the changes. You won't be able to undo those changes.", "Update fields", MessageBoxButtons.OKCancel) == DialogResult.Yes)
            {                                      
                con.Open();
                cmd = new SqlCommand(@"UPDATE Book 
                                        SET   BookTitle = '"+ txteTitle.Text
                                        +"', BookAuthorLname = '"+txteAuthorLname.Text
                                        +"', BookAuthorFname = '"+txteAuthorFname.Text
                                        +"', BookPrice = '"+ Convert.ToDecimal(eprice)
                                        +"', BookDescription = '"+txteDesc.Text
                                        +"', DatePublication = '"+dtpePublished.Value.Date
                                        +"', BookStock = '"+ Convert.ToInt32(estock)
                                        +"', isFiction = '"+ checkboxbool
                                        +"', BookCategory = '"+ cmbeCategory.SelectedValue
                                        +"'  WHERE ISBN = '"+ txteISBN.Text +"';", con);
                cmd.ExecuteNonQuery();
                con.Close();                   
            }

            BindEdit();
            BindGrid();
        }

This part of your line is wrong

..... MessageBoxButtons.OKCancel) == DialogResult.Yes)

you should check for DialogResult.OK otherwise you will never enter the update code

..... MessageBoxButtons.OKCancel) == DialogResult.OK)

Said that, please stop a moment and take a bit of your time learning how to create parameterized queries . These are the only correct way to write code that interacts with a database. String concatenation is really a bad practice and leads to Sql Injection attacks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM