I have a Winforms application and database to save data from user.
When I insert data everything works fine but when I clean the solution and load the GUI of the database to see the old data.. I don't see the datam the datagridview is empty.
using (SqlConnection con = new SqlConnection(dataBase.Connection.ConnectionString))
{
using (SqlCommand wow = new SqlCommand("insert into GamesTbl(Type,Date,Time) Values(#type,#date,#time)", con))
{
wow.Parameters.AddWithValue("#type", "vsPC");
wow.Parameters.AddWithValue("#date", DateTime.Now.Date);
wow.Parameters.AddWithValue("#time", DateTime.Now.TimeOfDay);
try
{
con.Open();
wow.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
What is wrong?
EDIT: binding data on DBGui_load
private void DBGui_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = playersTblBindingSource;
playersTblBindingSource.DataSource = DB.GamesTbls;
}
EDIT: my connection string:
"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated
Security=True;User Instance=True"
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Database1 - or while you're at it - give it a more sensible name...)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Seems liks you are missing DataBind.
private void DBGui_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = playersTblBindingSource;
dataGridView1.DataBind(); // you are missing this
playersTblBindingSource.DataSource = DB.GamesTbls;
}
As an alternative solution, what you can do to fix the problem is to set the property of your database file in your solution as follows
Copy To Output Directory: do not copy
Related
I don't get it why my (very simple) code is working properly on my local machine from Visual Studio 2022 and on the local IIS 10 to connect to a sql server express (15) and on my webserver it's not. I'm sure that's a really simple quesion for you.
What I'm tryin' to do is a simple login page. My code in the Login.aspx is:
using System.Data;
using System.Data.SqlClient;
try
{
SqlConnection con = new SqlConnection(#"Data Source=BERLIN\SQLEXPRESS;Initial Catalog=membersarea; User ID=sa;Password=Test2022!");
SqlCommand sqlCmd = new SqlCommand("select * from useraccount where username=#userName and passWord=#Password", con);
sqlCmd.Parameters.AddWithValue("#userName", tbxUsername.Text.ToString());
sqlCmd.Parameters.AddWithValue("#passWord", tbxPassword.Text.ToString());
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
DataTable datatable = new DataTable();
sqlAdapter.Fill(datatable);
con.Open();
int i = sqlCmd.ExecuteNonQuery();
con.Close();
if (datatable.Rows.Count > 0)
{
Session["userName"] = tbxUsername.Text.ToString();
datatable.Dispose();
Response.Redirect("Content.aspx");
}
else
{
lblMessage.Text = "Benutzername oder Passwort falsch.";
lblMessage.ForeColor = System.Drawing.Color.DarkOrange;
lblMessage.Visible = true;
}
}
catch(Exception ex)
{
}
(I know that I'm not supposed to do this with the sa account, just to keep it simple... The only thing I do on the web server is to change the name of the sql server instance. Management Studio works fine with this User Id and Password on my web server. I installed the sql server using Plesk and I don't think it is working properly within plesk. Using the Management Studio I can restore backups, queries, create new accounts, etc.)
My Content.asps says Hi (including my name) and shows the Logout-Button. If you enter credentials that are not correct it says so and if you try to go to the content-Page without loggin' in you're redirected to the Login-page. That is what I want. Trouble is, it's not workin' on my webserver. It is simply doin' nothing. No error message, or something else. It takes a while, password is cleared again and username is still there. (Doesn't matter which credentials are used.)
I don't think that it comes to the first line of my code, and I don't know why. Are there DLLs that are needed, or what else did I forget? I'm pretty sure this is a absolute beginner problem but I can't figure it out.
Tried to fill in some code to alter the lblMessage, to find out where the problem starts, but nothing of it is displayed.
I think the trouble started when I checked the pattern web forms while creating the project. In the bin folder there is a "name-of-my-project".dll and a "name-of-my-project".pdb file. Those two are generated if you recreate your project. I'm pretty sure you guys know that - I did not. Or better I do know that they were generated, but not that they are necessary. (As I wrote before, I'm at the very beginning.)
In guess that in this *.pdb and/or *.dll the connection string is stored, too. When I recreate my project with the valid connection string for the web server and upload them, too - everything works as expected. Thank you, guys for your ideas.
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."
I have a problem,
private void button_Submit_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=Database_TouchPOS.sdf;Persist Security Info=False;";
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
using (SqlCeCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "INSERT INTO Product (Title,Price,Category_Id) VALUES (#title, #price,#category_Id)";
command.Parameters.AddWithValue("#title", textBox_Title.Text);
command.Parameters.AddWithValue("#price", textBox_Price.Text);
command.Parameters.AddWithValue("#category_Id", comboBox_Category.SelectedIndex);
command.ExecuteNonQuery();
MessageBox.Show("Product Added Successfully...");
}
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Everything seem to be fine, but still can't add data into database.
I did try with complete database path, example c:\project\database.sdf
I did a lot of search before asking. I saw similar problems but not even a single one works for me.
Data are added when compiling but not committed to database. I can see the data after second attempt of debugging.
Please kindly try to explain in detail.
Thanks
You are probably facing this, http://erikej.blogspot.com/2010/05/faq-why-does-my-changes-not-get-saved.html suggest you use a full path to your database file in your connection string.
Did you try to use transactions explicitly?
IDbTransaction transaction = connection.BeginTransaction();
//add to database
transaction.Commit(); // before close connection
This is a very old thread, so I don't know if it will help anyone if I put my answer.
I had this problem, too.
When I executed an update or insert code in C#, apparently, everything was ok, but when I looked up the database, there was no change.
The thing was that while debugging I had the database opened in a Management Studio. And somehow this obstructed the database changes even when there was no error message.
Closing the Management Studio and opening it after executing the code, the changes where perfectly stored in the data base.
Regards.
complete example for those seeking like me... #"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";
thank for this example. This saved my day.
i wanna to attach a Database from a dynamic path to a MSSQL server by coding a project to do this ,,
what is the code i should write and will it be a Windows Application or Console Application ,, or there is no difference ??
You can use any of the two. Just make sure the files are in a place the SQL Server in question can reach and then attach them with an sql statement.
Like this:
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’C:\Data\AdventureWorks_Data.mdf’ ),
( FILENAME = N’C:\Data\AdventureWorks_Log.ldf’ )
FOR ATTACH
In the connection string you can attach a database if the database has not already been attached. To do this in C# you should be able to do the following (this is untested):
SQLConnection conn;
try
{
conn = new SQLConnection(String.Format("Server={0};AttachDbFilename={1};Database=dbname; Trusted_Connection=Yes;", "Server Address", #"Path To Database"));
conn.Open();
conn.Close();
}
catch (Exception ex)
{
throw;
}
finally
{
conn.Dispose();
}
Let me know how you get on.
Regards,
Stu
Are you talking about using System.Data.SqlConnection class?
You can dynamically build your connectionString when you create your SqlConnection.
If I nderstand your question correctly, you are looking for a way to use a databse which the user will select (not the hard coded one).
Go here and learn about Saving User and Application Settings in WinForms. You will get some ideas.
I have a SQL Server database in a C# project.
I use a connection string to connect to it.. I can use the method ExecuteNonQuery to insert data, no problem there.
But when I delete, it only deletes it momentarily, as soon as I restart the application it kind of rolls back the deletion.. Any ideas?
PS: I tested the string in a direct query, and it worked fine there.
public void executeNonQuery(string input)
{
db.Open();
SqlCommand cmd = new SqlCommand(input, db);
cmd.ExecuteNonQuery();
db.Close();
}
EDIT: DELETION CODE:
private void buttonSletPost_Click(object sender, EventArgs e)
{
if(dataGridView1.GetCellCount(DataGridViewElementStates.Selected)>0){
for (int i = 0;i < dataGridView1.GetCellCount(DataGridViewElementStates.Selected); i++)
{
String str1 = String.Format("WARNING about to DELETE:\n {0} \n BE CAREFULL NO TURNING BACK NOW!", Regnskab.getInstance().dbSelectPostID(dataGridView1.SelectedCells[i].Value.ToString())[0].ToString());
if (MessageBox.Show(str1, "Confirm Deletion", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string str = String.Format("DELETE FROM PostTable WHERE PostID={0}", dataGridView1.SelectedCells[i].Value.ToString());
Database.getInstance().executeNonQuery(str);
Console.WriteLine(str);
}
}
}else {MessageBox.Show("No cells selected");}
}
Which will give following output:
DELETE FROM PostTable WHERE PostID=7
Connection string in app.config:
<connectionStrings>
<add name="EndProject.Properties.Settings.DBtestConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBtest.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" />
private Database()
{
string connStr = ConfigurationManager.ConnectionStrings["EndProject.Properties.Settings.DBtestConnectionString"].ConnectionString;
db = new SqlConnection(connStr);
}
And then I open and close it, so the connection ain't open each time.
To be honest:
I don't exactly know where to see my DB info, here's some info from properties in VS2010.
Provider: .NET Framework Data Provider for SQL Server
Type: Microsoft SQL Server
Andrew's 3rd: I think they are deleted momentarily because I reloaded the information in my datagridview and from there it is gone. But then when I close the application and start it again, it is back...
Also i just checked with VS2010's server explorer and did a "Show Data" after I deleted (before I shut it down) and it wasn't deleted.
But I'm totally clueless now. :-(
Many applications use Transactions to manage db connections. SQL Server doesn't do it by default, but other factors in your application may be doing this.
Also, if you're really doing this, and your input is coming from a user interface, I can't wait to introduce you to Little Bobby Tables
Use the SQL Server Profiler to run a trace and capture the actual T-SQL statements that are getting executed on the database.
This is the easiest solution.
The behavior you're describing sounds like autocommit is off. Try the following and see if the record(s) stays deleted:
public void executeNonQuery(string input)
{
db.Open();
using (var txn = db.BeginTransaction())
{
SqlCommand cmd = new SqlCommand(input, db);
cmd.Transaction = txn;
cmd.ExecuteNonQuery();
db.Close();
txn.Commit();
}
}
Ok it was apperently me who was mistaken on the inserting part...
Someone suggested that i was because of the Visual Studio databases created every time the applikation ran.
So i installed MS SQL 2008 R2. Created a new DB with same layout.
Changed the connection string
And wuupti woo it seems to work, ill come back to this thread if it breaks down later..
But delete + insert both working greatly now :-)
Thanks to all who tried to help!