Values added in the GridView are not saved in the database - c#

Here is my following code:
string csr = "connection string";
string add = "Insert INTO table (Column1,Column2,Column3) Values (#Column1,#Column2,#Column3)";
using(SqlConnection connect = new SqlConnection(csr))
{
using ( SqlCommand command = new SqlCommand(add,connect))
{
command.Parameters.AddWithValue("Column1",textbox1.text");
//and so on
connect.Open();
command.ExecuteReader();
connect.Close();
}
}
I can see the data added in the gridview but when I check the table data in c# is empty, no value added. what's wrong?

You shouldn't have the connect.Close();, the using statement will take care of that for you.

command.Parameters.AddWithValue("Column1",textbox1.text")
should be
command.Parameters.AddWithValue("Column1",textbox1.text)
Set a breakpoint and ensure your connectionstring was properly set, textbox has a value, etc...

Related

Retrieve values from a RESTORE LABELONLY operation

I want to retrieve the resulting value of the following query :
RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak';
After doing some search I tried:
string connection = #"data source=.\SQLExpress;initial catalog=DB;persist security info=False;user id=sa;password=12356;MultipleActiveResultSets=True;App=EntityFramework";
ExecuteSQL(connection , #"RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak'");
And, the ExecuteSQL is:
private void ExecuteSQL(string ConnString, string sqlText)
{
string result = "";
using (SqlConnection sqlCon = new SqlConnection(ConnString))
{
sqlCon.Open();
using (SqlCommand sqlCom = sqlCon.CreateCommand())
{
sqlCom.CommandType = CommandType.Text;
sqlCom.CommandText = sqlText;
sqlCom.CommandTimeout = 0;
try
{
string str = Convert.ToString(sqlCom.ExecuteScalar());
}
catch (Exception e)
{
result = e.Message;
}
}
}
}
BUT .. the str always empty !!
The result of the query in SQL Server Management Studio is:
What I want is how can I retrieve the MediaSetID field?
MSDN says about the RESTORE LABELONLY operations:
Result Sets
The result set from RESTORE LABELONLY consists of a single row with
this information.
MediaName nvarchar(128) Name of the media.
...
So you have to use ExecuteReader method and process the columns in the returned reader (or load it to DataTable and do the same).
You should be using ExecuteReader() instead like below since your said command returning non-scalar value. You probably getting empty string cause the first column value of the RESTORE command is NULL per your posted SSMS result image
sqlCom.ExecuteReader()

Doesn't save added value into database

In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.

populating a text box with lloyalty points from a access database;

Im trying to populate a text box with infromation that is searched by using a customerID which is inputted throught a text box here is the code im using below
private void txtCustomerID_TextChanged(object sender, EventArgs e)
{
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
txtPoints.Text = sqlPoints;
}
but the text box "txtPoints" only outputs the text of the sqlpoints and not the information in the database? I'm not exactly sure what im doing wrong here.
Any help is appreciated, thanks in advance.
You are not executing the SQL statement on the database. Instead, you are assigning it to txtPoints.Text. You need to execute it on the DB server using, e.g., an OleDbCommand object.
What you need to do instead is something like the following (note this is pseudo-code - I haven't tested it runs)
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn)
// Create a reader containing your results
using(OleDbReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
}
Note also my use of using. This will ensure that your database connections are properly closed once you are finished with them.

How to properly initialize a .NET OleDbConnection object and its ConnectionString property?

This is my C# code to connect and work with an Access database.
using System.Data.OleDb;
var cb = new OleDbCommandBuilder(da);
DataRow dRow = ds1.Tables["Customer"].NewRow();
dRow[0] = textBox1.Text;
dRow[1] = textBox2.Text;
dRow[2] = textBox3.Text;
ds1.Tables["Customer"].Rows.Add(dRow);
da.Update(ds1, "Customer");
con.Close();
MessageBox.Show("Entry added");
But the line da.Update(ds1,"Customer");, throws an exception:
The ConnectionString property has not been initialized.
I'm not following your question too well, but here's some sample code that may help you figure out whatever it is that you are trying to do.
For clarity: The database is named "MyDb.accdb" and has a table named "Customer" which has two fields "Name" and "Phone". This example assumes the database lives in the same directory as the executable.
private void AddCustomer(string customerName, string customerPhone)
{
string name = customerName;
string phone = customerPhone;
// An easy way to determine the connection string to your database is to open the database from Visual Studio's 'Server Explorer'.
// Then, from Server Explorer, view the Properties of the database - in the Properties you will see the "Connection String".
// You can/should replace the arbitrary part of the path with "|DataDirectory|".
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|MyDb.accdb;Persist Security Info=True";
// Create your sql query in a string variable
string cmdText = string.Format("INSERT INTO Customer(Name, Phone) VALUES('{0}','{1}');", name, phone);
// Use the 'using' statement on your connection so that the resource is managed properly
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connString))
{
// Here's where/how we fire off the INSERT statement
OleDbCommand cmd = new OleDbCommand(cmdText, connection);
connection.Open();
cmd.ExecuteNonQuery();
}
}

Adapt beginner C# SQL Server INSERT example to work with my database

I have read TONS of tutorials, articles and whatever regarding my issue and honestly, due to my lack of experience I can't twist my fingers around this one so I hope some of you guys can help me out :)
I am working on a project (simply to learn how to program so it's probably very basic), but I have this "News" page where I can update and delete data using a GridView.
Now I would like to INSERT something into my database using 3 textboxes and 1 submit button.
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
Which are stored under NyhedTB from the connectionstring: BoligStjernenConnectionString
My query looks like this:
INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst])
VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)
I read on the internet that this code should do the magic for me (I will have to insert my own values ofc.):
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I looked at this code and thought it should be easy enough but really, I can't figure it out.
Here is some advice to get you going, learning programming is a lot of
trial and error.
Start off basic, litrally put three textboxes on a form/page and a
button.
Double click the button to go the code-behind and view the buttons
click event.
Paste in the body of code included with your question (everything in the try-catch).
Put a break-point on the Public Void Button_Click line of code and press F11 to
step through the code.
"one thing is having the code-behind working but how to make the buttons and textboxes working is still a misery"*
Put the textbox as the value rather than your hardcoded values:
cmd.Parameters.AddWithValue("#Address", textBox1.Text);
You also should not insert the Id value, instead modify the EmployeeDetails table and set the ID column to in the properties set Identity Specification (IS Identity) = True. Then right click the ID column and set Primary Key.
Post any error messages you encounter here and when you do get get it working, an additional exercise (that will be very valuable for you) would use a database stored procedure rather than ad-hoc SQL, to safe-guard against sql-injection attacks.
I'm assuming you have SQL Server installed and have a 'employee' database with a table called EmployeeDetails.
protected void GvManualShows_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//label lbl = (label)e.Row.FindControl("lblHidden");
if (e.Row.Cells[14].Text == "Y")
{
// CheckBox cb = (CheckBox)e.Row.FindControl("chk");
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkBox");
chk.Checked = true;
}
}
}
It's fairly simple. You just have to modify the connection string, the query and its parameters:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString =
"server=SQLServer;" + // SQLServer is your SQL server machine
"initial catalog=employee;" + // employee is your database
"user id=sa;" + // sa is the login to connect the database
"password=sa123"; // sa123 is the password of the login
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst]) " +
"VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
cmd.Parameters.AddWithValue("#NyhedDato", textBoxDate.Text);
cmd.Parameters.AddWithValue("#NyhedTitel", textBoxTitle.Text);
cmd.Parameters.AddWithValue("#NyhedTekst", textBoxBody.Text);
int rows = cmd.ExecuteNonQuery(); // Inserted rows number
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I made changed example code with your requirements and added comments, hope it would be a bit clearer for you to understand whats going on:
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=MyDatabaseName;" + //here you write database name where your NyhedTB table is
"user id=sa;" + //user name to connect to database
"password=sa123"; //password
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO NyhedTB (NyhedDato, NyhedTitel, NyhedTekst) VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
//all "things" in your sql command what beggins with #
//means that it is parameter and you need to pass values for these parameters:
//For #NyhedDato parameter you set text from your textbox
cmd.Parameters.AddWithValue("#NyhedDato", txtDate.Text);
//For #NyhedTitel parameter you set text from title textbox
cmd.Parameters.AddWithValue("#NyhedTitel", txtTitle.Text);
//For #NyhedTekst parameter you set text from content textbox
cmd.Parameters.AddWithValue("#NyhedTekst", txtContent.Text);
//Execute insert command and get how many records was efected, in this case it should be rows = 1 because you inserting just one record
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
P.s. code not tested. And when you say
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
actually you mean you want to insert record with fields

Categories