Insert a column value to database using session - asp.net

I want to insert a value into a table which comes from a session variable.The code that i have written is:
protected void Button1_Click(object sender, EventArgs e)
{
double balance;
double reward;
if((double.TryParse(lblBalance.Text, out balance) && (double.TryParse(lblReward.Text, out reward))))
{
Session["FinalBalance"] = balance + reward;
}
else
{
// some kind of error handling
}
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister('Balance') values('#FinalBalance')", con);
cmd.Parameters.AddWithValue("#FinalBalance", Session["FinalBalance"].ToString());
}
}
But when i click the submit button,the code doesnt throw any exception and doesnt insert the needful.What is the problem here?

You are making the command object but not executing the query. You have to call ExecuteNonQuery method on Command object to insert record.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister(Balance) values(#FinalBalance)", con);
cmd.Parameters.AddWithValue("#FinalBalance", Session["FinalBalance"].ToString());
cmd.ExecuteNonQuery ();
}

Related

Updating database from ASP.Net getting error "Connection property has not been initialized"

I am trying to retrieve a value from my database, increment it by 1, and then update the database with this new value.
My code so far is
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand("Select likeCount from tbl_Post where tbl_Post.Id="+Convert.ToInt16(content) , conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int oldVal = Convert.ToInt16(dr["likeCount"]);
int newVal = oldVal + 1;
SqlCommand insert1 = new SqlCommand("update tbl_Post set
likeCount="+newVal+ "where tbl_Post.Id=" + content);
insert1.ExecuteNonQuery();
conn.Close();
}
I am getting an error on the line insert1.ExecuteNonQuery
ExecuteNonQuery: Connection property has not been initialized.
The reason of your error is the missing connection in the second command. You can add it to the SqlCommand constructor as you do in the first command, also you have a missing space in the query text for the second command.
These errors and a more serious error called Sql Injection could be avoided if you use parameters like explained in the code below
Least but probably most important is the fact that you don't need two commands to increment the likeCount field. You can write a single command
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
string updateText = #"update tbl_Post
set likeCount=likeCount + 1
where tbl_Post.Id=#id";
using(SqlConnection conn = new SqlConnection(connStr))
using(SqlCommand cmd = new SqlCommand(updateText, conn);
{
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt16(content);
cmd.ExecuteNonQuery();
}
}
Notice also the presence of the using statement around the disposable objects like connection and commands. This allows you to close and dispose these objects also in case of exceptions.

ASP.Net Server prints data from DB but won't write to DB

I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!

stored procedure to delete entire table

I want to delete all the rows of a table on a button click.the stored procedure is as follows:
create proc spTest
as
begin
Delete from tblTest
end
The code-behind is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
but the table remains unaffected although the label shows all tasks deleted successfully. What is the problem? I know something is very silly that I am doing.
PS: I don't want to use Truncate.
You have created Command but did not execute it. You have to call ExecuteNonQuery in order to exeucte the Command
As a addition note, put the code in try-catch block so that your application does not terminated in case of exception
protected void Button3_Click(object sender, EventArgs e)
{
try
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
catch(Exception ex)
{
lblStatus.Text = "Tasks could not be deleted, Error " + ex.Message;
}
}
You have to execute the query using ExecuteNonQuery command.
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
}
You are never acutally executing your query.
Call it like this:
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
/*new:*/
cmd.ExecuteNonQuery();
lblStatus.Text = "Tasks Deleted Successfully.";
}
You are forgoted to execute the command.
add this cmd.ExecuteNonQuery(); to Button3_Click event
protected void Button3_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTest", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
if(cmd.ExecuteNonQuery()>0)
{
lblStatus.Text = "Tasks Deleted Successfully.";
}
else
{
lblStatus.Text = "Unable to Delete tasks";
}
}
}

link data from Textbox to SQL Database in ASP.net (C#)

I am attempting to create a web form where data from several text box's will enter data into a n SQL database I have created. My code is listed below, and the problem is that when it compiles, it acts as if it hasn't. The messagedisplay.text does not change, and the SQL database does not update. Does anyone know a solution?
protected void createButton_Click(object sender, EventArgs e)
{
string state = stateTextBox.Text;
string country = countryTextBox.Text;
string lake = lakeTextBox.Text;
SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO ResearcherID VALUES(#ResearcherFname, #ResearcherLName)", connection))
{
command.Parameters.Add(new SqlParameter("ResearcherFName", country));
command.Parameters.Add(new SqlParameter("ResearcherLName", state));
command.ExecuteNonQuery();
}
messageDisplay.Text = "DB Connection Successfull";
}
catch
{
messageDisplay.Text = "DB Connection Failed";
}
}
try this
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (#ResearcherFname, #ResearcherLName)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("#ResearcherFname", country);
sqlCmd.Parameters.AddWithValue("#ResearcherLName", state);
}
Also use connection.Open(); inside try

sql data reader class

I did sql command with SqlDataReader but I had this error
System.IndexOutOfRangeException: UserName
Page Load event:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("Total", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataReader Dr = Com.ExecuteReader();
if (Dr.Read())
{
string Result= Dr["UserName"].ToString();
Lbltotal.Text = Result;
}
}
}
Stored Procedure:
Alter proc Total
as
begin
select Count (UserName) from Registration
end
Change your storder procedure to:
Alter proc Total
as
begin
select Count (UserName) as UserName from Registration
end
You're not returning any column called UserName - you're just returning a count which has no explicit column name.
If you have something like this - just a single value - you could also use the ExecuteScalar method which will return exactly one value:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
int count = (int)Com.ExecuteScalar();
}
If you insist on using the SqlDataReader, you just need to use a positional parameter:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
using(SqlDataReader Dr = Com.ExecuteReader())
{
if (Dr.Read())
{
string Result= Dr[0].ToString(); // take value no. 0 - the first one
Lbltotal.Text = Result;
}
}
}

Resources