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.
Related
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.
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
Here is everything that I did:
In a visual studio 2013 C# project, I created a service database (.mdf file). Note: I changed the name from Database1.mdf to fghLocalDB.mdf.
I opened this database in the server explorer.
I created 2 tables called Country and CarbonDioxide using the table designer.
I added an entry to the Country table as shown by the Data Table of the Country table.
I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down.
This is what my project files looked like at this point.
I wrote the following code in the main method thinking that this would be all I need to write to the database.
// Create a connection to the DataSet and TableAdapters that will communicate with our
// local database to handle CRUD operations.
fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter =
new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
try
{
// Insert a row into Country table. EDIT 1 Will comment after first program run.
Console.WriteLine(countryTableAdapter.Insert("United States"));
// Actually writeback information to the database?
// dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
// EDIT 3 Validation code as suggested by Ley.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
adapter.Fill(dt);
foreach (var row in dt)
{
// This does not get executed after a second run of the program.
// Nothing is printed to the screen.
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
}
catch(SqlException exception){
Console.WriteLine("ERROR: " + exception.ToString());
}
Console.ReadLine();
I ran the program and everything seemed fine.
I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
The "United States" row was not added as wanted.
I think it has to do with the connectionstring. I right clicked on my project and opened properties.
Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same.
I copied and pasted the actual text for each connection string:
Connection string of project:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Connection string of actual database (.mdf file):
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.
My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?
If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?
I read the following links:
Insert method of TableAdapter not working?
TableAdapter Insert not persisting data
Use connectionstring from web.config in source code file
Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?
I never used tableadpter.insert() method. But I tried it on my local machine, and it works.
I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.
If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.
var countryTableAdapter = new CountryTableAdapter();
countryTableAdapter.Insert("United States");
This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.
The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.
var rowAffected = countryTableAdapter.Insert("Test2")
If you need more confirmation , try this.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
you will see all the records in your table.
I hope this will help.
By the way, from your code
dataSet.AcceptChanges();
The line of code above doesn't update the database at all. It only modify your local data storage.
it overwrites your dataRow original version using current version and change the current version row state to unchanged.
Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly).
And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.
The tableAdapter.update method will call AcceptChanges on each row eventually if it successfully updated the database.
You should never need to call AcceptChanges explicitly unless you only want update your dataset in memory.
I recommend you to read ADO.NET Architecture to get the big picture how DataSet and TableAdapter worked.
It was my connection string after all. In my original post, I said I had two connection strings:
Connection string in project settings:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Actual connection string in fghLocalDB.mdf file:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
Something went wrong with
|DataDirectory| = C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;
in my App.config.
My Solution:
What I did was copy the actual connection string of the .mdf file from the .mdf properties panel and paste it into the project properties => Settings => Value field of the connection string set up.
Afterwards I ran my code again and sure enough the data persisted in the tables.
I did not need dataSet.AcceptChanges(); as #LeY pointed out. I also did not need a TableAdapter.Update(dataset) call as posted in other solutions. I just needed the TableAdapter.Insert("...") call.
EDIT: ALSO Most importantly to answer my original question, instantiation a DataSet does not create a connection with the local database. Instead instantiating a TableAdapter does establish a connection with the database!
For some reason, I can't open the Design View of the MS Access table in question; I can look at the data but not the desing, specifically, the length of columns.
When I try to insert a record into said table with this code:
using (var conn = new OleDbConnection(connStr))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText =
#"INSERT INTO tx_header (tx, site_no, xmlfile, collect_dttm, ccr_user, tx_memo, file_beg, file_end)
VALUES(#txval, #siteNum, #xmlfileName, Now(), #ccrUser, #TXMemo, #strfile_beg, #strfile_end)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#txval", tx);
cmd.Parameters.AddWithValue("#siteNum", site_no);
cmd.Parameters.AddWithValue("#xmlfileName", xmlfile);
cmd.Parameters.AddWithValue("#ccrUser", ccr_user);
cmd.Parameters.AddWithValue("#TXMemo", tx_memo);
cmd.Parameters.AddWithValue("#strfile_beg", file_beg);
cmd.Parameters.AddWithValue("#strfile_end", file_end);
conn.Open();
cmd.ExecuteNonQuery();
}
}
...I get, "System.Data.OleDb.OleDbException was unhandled by user code
HResult=-2147217833
Message=The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.
Source=Microsoft Office Access Database Engine"
Rather than have to guess which column has too much data, it would be nice if I could programmatically determine which column is the problematic one. Can I? How?
There's a pretty detailed explanation of how to query the underlying schema information in MSDN, starting at Retrieving Database Schema Information.
Disclaimer: I've never tried using that against an Access database.
After reading your comments above it looks clear to me that your Access file simply has its designer views locked down. Normally you should be able to unlock them by simply holding Shift, double-clicking the file and keep holding Shift until Access is up and running.
From then on you'll have complete access to tables, queries and the like, and along with it, your database specifications. That will be far better than trying to access that dynamically.
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."