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";
}
}
}
Related
here is my code
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string constr = #"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string query = "Insert into [dbo].[student] ([ID],[NAME],[DOB],[GENDER]) Values ('#id','#name','#dob','#gender')";
Label3.Text = "execute";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", TB1.Text);
cmd.Parameters.AddWithValue("#name", TB2.Text);
cmd.Parameters.AddWithValue("#dob", TB3.Text);
cmd.Parameters.AddWithValue("#gender", rm);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
protected void Button3_Click(object sender, EventArgs e)
{
try
{
string constr = #"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True;";
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string query = "Update [dbo].[student] set [ID]=#id,[NAME]=#name, [DOB]=#dob," +
"[GENDER]=#gender Where [ID]=#id";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", TB1.Text);
cmd.Parameters.AddWithValue("#name", TB2.Text);
cmd.Parameters.AddWithValue("#dob", TB3.Text);
cmd.Parameters.AddWithValue("#gender", rm);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
Refer this coding. if any doubt let me know
cmd.Parameters.AddWithValue("#dob", DateTime.Parse( TB3.Text)));
Suddenly my register button is not performing any action other that validations. any idea?
here is my registration.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand();
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
cmd.Connection = con; //assigning connection to command
cmd.CommandType = CommandType.Text; //representing type of command
cmd.CommandText = "INSERT INTO UserData values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
//adding parameters with value
cmd.Parameters.AddWithValue("#Username", txtUser.Text);
cmd.Parameters.AddWithValue("#Firstname", txtFN.Text);
cmd.Parameters.AddWithValue("#Lastname", txtLN.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", (txtPW.Text));
cmd.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
cmd.Parameters.AddWithValue("#Zip", txtZip.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
con.Open(); //opening connection
cmd.ExecuteNonQuery(); //executing query
con.Close(); //closing connection
label_register_success.Text = "Registered Successfully..";
}
else
{
label_register_success.Text = "Please check the registration errors";
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs arguments)
{
string UserName = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", UserName);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs arguments)
{
string Email = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Email=#Email", con);
cmd.Parameters.AddWithValue("#Email", Email);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
Its not performing the successful registration and the validations for the repeated username and email. please help me out, thanks!
Try triggering the validation via:
Page.Validate();
And pass in any validation groups you use as the parameter (if applicable) before checking IsValid, and see if that detects the errors. I assume your Validate methods are called from CustomValidator controls?
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!
I do not understand why I have this error message. No code is used for the connection, only an SQLDatasource and a grid view. I am using this code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
ListBox1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
Label1.Text=ex.Message;
}
}
First you have install oracle data access client and then try this
following code
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source = DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = ho
List item
st_name)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = your_service_name)" +
")" + ");User Id = ID;Password=Password;";
Oracle.DataAccess.Client.OracleConnection con = new Oracle.DataAccess.Client.OracleConnection();
con.ConnectionString = connectionString;
con.Open();
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.CommandText = "select ref_no from money_trn where ref_no=20170733";
cmd.Connection = con;
con.Close();
cmd.CommandType = System.Data.CommandType.Text;
Oracle.DataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
TextBox1.Text = dr.GetString(0);
}
You can't use SqlConnection for the Oracle!
First of all, you have to add connectionString into web.config to connection with Oracle.
Secondly, Add reference System.Data.OracleClient to your project.
Then, replace SqlConnection with OracleConnection. Everything, what you used with Sql, you have to replace with Oracle.
I have written a code to insert the data to SQL LITE database as follows
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 0;
Session["x"] = "session value";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
string txt="insert into stu values("+TextBox1.Text +",'"+TextBox2.Text+"')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = txt;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
}
After inserting while retrieving data Session is getting null I don't know why
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["x"] != null) // Getting Null here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
DataSet m_oDataSet = new DataSet();
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string txt = "select * from stu";
cmd.CommandText = txt;
SQLiteDataAdapter adp = new SQLiteDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(m_oDataSet);
GridView1.DataSource = m_oDataSet.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
finally
{
conn.Close();
}
}
}
The same code when tested in Sql server 2008 works fine
protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cnstr);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
if (Session["x"] != null) //Able to get session here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
}
}
My sql lite path is from Bin folder as shown in image
your app writes to DB (which is in BIN folder). That causes app restart => in-proc session gets lost. You should NOT solve the consequence (by using StateServer mode), you should fix the original reason - move db file into another folder, away from BIN folder.