Home > Enterprise >  Button not updating the database
Button not updating the database

Time:10-31

I want to give the users to the ability to update their info on database. I made the button to for the software to take the name from one of the textboxes and send it to the database.

public void Updatebtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");

    con.Open();

    SqlCommand cmd = new SqlCommand("Update Users set First_Name=@fn WHERE ID = '2' ", con);
    cmd.Parameters.AddWithValue("@fn", UFirstName.Text);

    cmd.ExecuteNonQuery();

    con.Close();
}

I watched a YouTube video and followed step by step. But it didn't work. The button works and executes command. But something is wrong with either sql command or connection because the database doesn't get updated

CodePudding user response:

because your codes seems okey to me with no problems in it i'll give you some tips that will make sure you almost avoiding most mistakes biggeners like me did which caused unexplaind errors.

these tips will REALLY REALLY help you in your programming journey.

  1. when adding a new local database, create a newfolder and name it DataBaseFolder as an example inside your project folder , so you always know where is your database and you dont get confused about other databases in the default location VS saves them, and its better that the project folder is placed in the partition "C" in a default folder of windows.

  2. when creating a new table, name it probably in the definition part at the bottom where you can see: create table [dbo].[TableName] then press Ctrl s, make sure to save that table in the same folder as your database, so you always know this table is for this project.

  3. )))) each time you update your table definition like column name or type, or adding a new column or deleting an existing one, make sure to press Ctrl s and save the table (replace) in the same folder you originally created it, that will make sure you don't get the error most new developers like me were stuck at which is the update window is taking forever to preview the changes.

  4. ))))) to make it easy for myself to use the sql commands, i created a script (class.cs) and put the important codes in methods with parameters so i save a lot of time when i was restarting over my program because of some mistakes i did :D

first i defined my sql connection in the class named SqlCodes:

SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");

then i created my methods, examples:

public void QueryCommand(string QueryString) 
{
con.Open();
SqlCommand cmd = new SqlCommand(QueryString, con);
cmd.ExecuteNonQuery();
con.Close();
}

public void FillingDataGridView(parameter1,parameter2, parameter3) 
    {
    con.Open();
   some code;
    con.Close();
    }

So, back to my main class where my button will function:

SqlCodes sqlCodes = new SqlCodes();

in the button i now can write:

sqlCodes.QueryCommand("insert into MyTable values (your values)");

or

sqlCodes.RefreshDataGridViewAfterEntry (parameter1,parameter2,parameter3)

or

string queryCommand = " insert into MyTable values (your values)";
sqlCodes.QueryCommand(queryCommand);

or in the load form method so when you open the program it shows the data you want instantly

{
sqlCodes.FillingDataGridview(parameter1,parameter2,parameter3)
}
  1. if you're having errors with your database, don't delete the files you will find in the solution explorer because it will cause you some errors i couldn't figure their solution, just delete the database in the server explorer, and don't forget to change the sql connection path in the SqlCodes Class you created.

that will save you time and and to avoid errors and make your code very simple, instead of copy paste/ writing about 7 or 8 lines each time you want to do something with your database.

CodePudding user response:

I managed to solve the problem. As it Turns out. clicking the button also calls page_load. Which has a code that replaces text in the textbox. So the button would first call page_load. Retrieving data from the databox. Then it would put in the textbox.

Then it would take data from the same textbox again and send back it to the database.

I managed to fix it by putting the code in pageload inside in if statement. And then i put !Page.IsPostBack condition inside the if statement.

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Active"] != null && Session["Active"].ToString() 
            =="Yes" && !Page.IsPostBack)
            {
                GetUserData();
            }
            
        }

Hope that helps.

  • Related