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
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.
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.
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.
)))) 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.
))))) 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)
}
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.
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
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString);
public Form1()
{
InitializeComponent();
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Inserted!");
}
}
Given that it's Ole, I'm guessing this is Access - a file based database. Your insert is running successfully but you don't find the data in the db when you look
You need to appreciate that typically withba probe t that uses an access db you will have several copies of the db but the most relevant ones are probably like:
C:\myprojects\windowsapp1\your.accdb
C:\myprojects\windowsapp1\bin\debug\your.accdb
The first one is the db you see in the solution explorer. The second one is placed next to your debug exe every time you run a build, or possibly every time you click play in VS. The second one is probably the db your program is inserting into
You're either looking in the wrong db for your data, or every time you run your program the build process erases the changes db by copying the empty one (first one) over the top of it.
Run your app, insert your data, don't quit your app, Search your entire project folder for all instances of your db file. Look in all of them. You'll probably find your data
Right click the db file in solution explorer, choose properties, and change the Copy action to Copy If Newer
Now the build process will only erase your db in the debug folder if you make a change to the source db, eg add a table to it etc
I have a data table, in the data table, I have 3 columns: USERNAME, PASSWORD, and Money.
I want to make a specific setting in my program to make a label the amount of money the user has, and for each user, it will show something else depending on who is logged on at the moment, is it possible and if yes how can I do it?
Thanks in advance.
You can put the amount of money in your label by writing some code. This is used for MSSQL Database connections(in your case).
Here is an example:
using System.Data.SqlClient;//Add this in the using statements at the top of your code.
using (SqlConnection conn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename =" +Application.StartupPath+ #"\Database1.mdf; Integrated Security = True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Money FROM Users WHERE Username = #username";
cmd.Parameters.AddWithValue("#username", "User1");
var reader = cmd.ExecuteReader();
reader.Read();
label1.Text = reader.GetValue(0).ToString(); //reader returns an object, you have to convert it in your type.
//GetValue(selected column number)
}
conn.Close();//This line is optional. The connection closes automatically when the using() statement ends.
}
You can add this code in your Form Load event.(If you are working with Win Forms).
The second method is to use Dataset with binding the label to it. This is also powerful and you do not need to know too much sql or how to code, it is more complicated at the beginning but it`s easier and saves time. You can apply it to any of your form elements(buttons, datagridviews,combobox,textbox,etc).
First, go to your label properties and find "DataBindings". Click on advanced. Just click next until you see the connect to database option. If your are connected already with visual studio to your database it will appear in that combobox, otherwise click new connection(I suppose you worked in service based database).Click next and finish. After you have to bind the label to the database(it will create a generated code in your Form Load Event). If you have only one record(one user) in the table it will show only one value, but if you want to show a specific user, you can change that "Fill" generated method in your Form Load Event in other(filtered one with WHERE SQL Clause). You can change that fill method in the Dataset Added in the bottom of your designer of the form. Click on that little arrow near it and choose "edit in designer" option. Click on the table adapter section and right click on his function(in this case Fill() method) and click configure. Here you can change the sql statement and put a WHERE clause in the end.(ex Where Username = ?) The "?" means some variable. After pass in the function created in the form load event your user`s username next to that dataset thing. Done. If you want to work with Win Forms and sql databases I advise you to learn how to use The Datasets, Bindings and TableAdapters. Hope it helps.
Screenshots of my explanations:
!!!! [UPDATE] !!!!
Here is my example program on google drive: Link.
On the right side you can open my service based database(in the project files(Database1)).I'll attach some useful screenshots for creating addition functions in a dataset's table adaper. Also, you have the second method commented in the Form1 load event.
This question already has answers here:
Why saving changes to a database fails?
(2 answers)
Closed 5 years ago.
:)
I've started with project of creating some program for Library. I mean, it is a simple program which has login form and some features for admin. Also, I've done database (everything is done with Visual Studio 2013), SQL Service-based Database. I followed some Youtube tutorials and now when I added button for adding users in database I run into "problem". This is code for Add button:
private void btnAdd_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.KnjiznicaDBConnectionString"].ConnectionString;
string query = "INSERT INTO User VALUES(#Name,#Surname,#Year,#Mail)";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
{
connection.Open();
command.Parameters.AddWithValue("#Name", txtName.Text.Trim());
command.Parameters.AddWithValue("#Surname", txtSurname.Text.Trim());
command.Parameters.AddWithValue("#Year", txtYear.Text.Trim());
command.Parameters.AddWithValue("#Mail", txtMail.Text.Trim());
command.ExecuteScalar();
}
}
Now, I know that user is added into database, because I can see it in DataGridView which is also in Form, but when I check directly in Database (I mean in Server Explorer->Database_name->Tables->User (Show Table Data)), that new user is actually not added there. And no matter if I exit Visual Studio, as long as I don't shut down computer, that new User will be in DataGridView but not in "Database". And when I restart computer and start Visual Studio again, new user won't be even in DataGridView. Only permanent users are those that I add directly through Show Table Data or with New Query also in Server Explorer.
I would like to know what should I correct so all users added through the code and Form are implemented in "real Database" not just DataGridView.
Thanks :)
Wrong command
You need SqlCommand.ExecuteNonQuery
And you would be wrapping open and command in Using blocks
Alright, I am going to try and be as thorough as possible. I have gone through several (many) tutorials before resorting to posting here if anyone is wondering /=
I have several tables - one contains text/stored-procedure-name pairs which will populate a dropdown menu on the front end (Web Form). The other tables are accessed via the stored procedures. The idea is that I want to be able to be able to control from the back-end which fields are viewable/editable to the user on the front end. I also would like to be able to add / remove stored-procedures to retrieve data without having to mess with the front end.
The user can select from the drop down, and based on the selection a stored-procedure will be executed and then populate the gridview. No problems so far.
Now, ideally, the user will be able to edit the data presented in the gridview. This is easy enough, until we start getting fancy (i.e. overriding the default textbox controls that get generated). For example, when the user presses "edit" in the GridView row, and a record has the datatype "DateTime", I want some sort of calendar/clock to pop up and allow the user to pick the date and time, and then update it back into the database.
I've been running into roadblocks at this point. I've followed the tutorial on dynamically generating editable gridviews (http://aspalliance.com/1125_Dynamically_Templated_GridView_with_Edit_Delete_and_Insert_Options.1), but it does not work with what I am trying to do.
Any help is greatly appreciated, and I hope I have explained this with enough depth!
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.setData();
}
public void setData()
{
//Establishing the SQL Connection
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString
))
{
//string query;
SqlCommand SqlCommand;
SqlDataReader reader;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
//Generating the query to fetch the contact details
//query = "SELECT * FROM " + DropDownList1.SelectedValue + ";";
SqlCommand = new SqlCommand(DropDownList1.SelectedValue, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
conn.Close();
} }
The issue is that when this gets triggered:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.setData();
}
All of the editable fields default to text boxes. I have been unable to get them to format according to datatype. Again, as an example, if the datatype is DateTime, a calendar should pop up and let user select date/time.
I know that there is a way to do it using except this is for statically generated gridviews. This gridview is dynamic and its contents depend on procedures executed from the backend, so I can't hardcode the edit formats into the front end.
Before I start, I'll let you know that I tried everything that has already been suggested on previous questions and other websites before I considered posting a question myself. As it happens, nothing seems to work and I'm just about fed up with this.
As some background information, this is for my Computing A2 project, so I'm kind of stuck for time now - i.e. I can't be changing loads of my code ideally.
Anyway, onto the issue...
I'm using SQLCe in my code to read from various tables and write to one. So far, the code for reading from the tables works fine, so that's any connection issues out the way first. The piece of code I am struggling with is as follows:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
This is just one of the many ways I have tried to combat the issue I am having. I have also explored:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
to pass the parameters...and another method which escapes me now (using ".Value = StaticUser.StudentUser.username" I think). Furthermore, I have tried using a 'using' statement for the command to save me closing the connection myself (I will probably end up using a solution that uses 'using'). Finally (albeit this isn't a chronological recollection), I tried:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)", myConnection)
Again, of course, to no avail.
To highlight the actual symptoms of the issue I am having: The code appears to run fine; stepping through the full method I have pasted above shows that no error is being caught (of course, the message box does not appear - I realised afterwards that stepping through was arguably an unnecessary procedure) and in the other methods I have touched on, the same thing happens. The issue, then, is that the table 'bookings' is not actually being updated.
So, my question, why?
I didn't do the obvious and check the Debug folder for an updated database.
Look for a copy of the database file in your bin/debug folder.
Use full path in connection string, and preferably do not include the sdf file in your project (or at least set build action to None)
i think you are not defining a connection for the command
try
mycommand.connection = connectiostring;