Cancel submit button event in ASP and C# - c#

I am trying to cancel a submit event if a response is true. I have a submission button in which i am wanting to check if the textbox is same as a value in the database. If it is then it will not allow the update to go ahead.
My C# code
protected void SubmitBtn_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
conn.Open();
string sql = "Select count(*) from Student Where Student_Username=#username";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists");
}
conn.Close();
}
//SQL Connection and SQL for inserting a new student
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
var sql = "INSERT INTO Student (Student_Username, Student_FName, Student_SName, Student_Email, Student_Password, Student_Status) " + "VALUES (#StudentName, #StudentFirstname, #StudentSurname, #StudentEmail, #StudentPassword, #StudentStatus);";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#StudentName", usernameTxt.Text);
cmd.Parameters.AddWithValue("#StudentFirstname", firstnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentSurname", surnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentEmail", emailTxt.Text);
cmd.Parameters.AddWithValue("#StudentPassword", passwordTxt.Text);
cmd.Parameters.AddWithValue("#StudentStatus", statusTxt.Text);
cmd.ExecuteNonQuery();
}
greenPnl.Visible = true;
usernameTxt.Text = "";
firstnameTxt.Text = "";
surnameTxt.Text = "";
emailTxt.Text = "";
passwordTxt.Text = "";
retypePasswordTxt.Text = "";
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
con.Close();
}
How can i call the eventArgs to cancel it? I know you cant simply e.cancel = true;

You can't "cancel" an event like that in ASP.NET. ASP.NET is a request/response platform - when you do something in the browser (click a link, submit a form, etc) - you send an entire request back to the server, and the browser waits for a response. That response will be rendered completely by the browser.
So some options are:
Continue with the ASP.NET lifecycle, completely rendering the page with whatever message you want to send back.
Use AJAX or some other mechanism to send a light request to the server before sending the entire request.

Related

Delete a record from database

I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.

Insert Data Into Databse Once User Clicks on Button

I am trying to write a code that will insert data into a database once user click on button. There's something wrong with the code and it does not seem to work properly. I connect to an external database based on my hosting provider.
private void druk_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=s59.hekko.net.pl;uid=truex2_kuba;" +
"pwd=test;database=truex2_kuba;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "insert into [barcode]values(#class, #tree, #type, #amount, #length, #width, #square)";
cmd.Parameters.AddWithValue("#class", klasa.Text);
cmd.Parameters.AddWithValue("#tree", gatunek.Text);
cmd.Parameters.AddWithValue("#type", rodzaj.Text);
cmd.Parameters.AddWithValue("#amount", amount.Text);
cmd.Parameters.AddWithValue("#length", length.Text);
cmd.Parameters.AddWithValue("#width", width.Text);
cmd.Parameters.AddWithValue("#square", textBox1.Text);
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Zapisane do raportu");
}
The issue is this:
MySqlCommand cmd = new MySqlCommand();
is in the scope of the try, catch block.
Further on in the code, there was a reference to the cmd variable which is null and hence no data goes in.
Move it outside of the try, catch block.

C# check userid already exists

I am designing a web form to insert data into sql database.I just want to check that email id which is unique already exists or not.
code:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox2.Text))
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("select shop_email from shop where shop_email=#email", con);
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Label1.Text = "email id already exists";
}
con.Close();
}
}
I tried above code but its not working i.e Label is not displaying anything.Any help will be thankful.
Problem : You are writing your code in TextBox_TextChanged Event handler so it would be invoked for everytime whenever there is a change in the TextBox and it would not give you the result untill unless you enter the complete Email-ID.
Solution 1: You need to write the above code in some Button Click Event handler as below:
protected void btnSearch_Click(object sender,EventArgs e)
{
//Write your code here
}
Solution 2: if you want to keep your code in the TextBox TextChanged Event handler but still want to identify the EmailID you can use LIKE operator instead of = operator
Try This:
SqlCommand cmd = new SqlCommand("select shop_email from shop
where shop_email LIKE #email", con);
cmd.Parameters.AddWithValue("#email", "'%"+TextBox2.Text +"%'"+);
try to add else statement in case if user/email does not exist
Also move this code to button click event or some other event. On Text Box text change event it will not return result.
using (var con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True"))
using(var cmd = new SqlCommand("select 1 from shop where UserID=#UserID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserID", TextBox2.Text);
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
Label1.Text = "userid already exists";
}
else
{
Label1.Text = "userid doesn't exists";
//Create new user
}
}
}

SQL Server Error, 'Keyword not supported 'datasource'

I'm currently trying to INSERT some values into a datasource, then display them on another page using the DataList control. However, after some testing and experimentation, I've found that the error comes from the very beginning.
Here is the code I have bound to my button.
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("DataSource=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName);
cmd.Parameters.AddWithValue("Phone", txtPhone);
cmd.Parameters.AddWithValue("Email", txtEmail);
cmd.Parameters.AddWithValue("Comments", txtComment);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
}
Here is the image of my webpage and the error it displays.
Please let me know if you need additional information.
Thanks in advance.
In your connection string, it should be "Data Source", not "DataSource". Just add a space.

Creating a sql connection in c#

I'm new to this site and also to programming. I am currently creating an inventory system via a point of sale. It uses modal and non-modal forms. My problem is tho, I'm working on the change password dialog which has to be connected to the database in order to overwrite the password field. The database i used is microsoft sql server management studio express. Here is what I have so far with the necessary comments. Please note that on the 'design' form, I have a combobox which is bounded to the database. Where did I go wrong?
private void ChangePwdButton_Click(object sender, EventArgs e)
{
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Gerald- dean Martin\Documents\SQL Server Management Studio Express\Projects\BodyMates.mdf;Integrated Security=True;User Instance=True";
sqlconn.Open();
string oldpwd = txtOldPwd.Text;
string newpwd = txtNewPwd.Text;
string confirmNewPwd = txtConfirmNewPwd.Text;
string sqlquery = "UPDATE [Employee] SET Pwd=#newpass where EmployeeCode=#empcode";
SqlCommand cmd = new SqlCommand(sqlquery, sqlconn);
cmd.Parameters.AddWithValue("#newpass", txtConfirmNewPwd.Text);
cmd.Parameters.AddWithValue("#empcode", comboEmpCode.SelectedValue);
//cmd.Parameters.AddWithValue("#pwd", txtNewPwd.Text);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(txtOldPwd.Text == dr["pwd"].ToString() && (txtNewPwd.Text == txtConfirmNewPwd.Text))
{
if (comboEmpCode.SelectedIndex == 0)
{
string query = "UPDATE [Employee] SET Pwd = '" + txtConfirmNewPwd.Text + "'";
}
}
// if ((txtNewPwd.Text == dr["newpwd"].ToString()) & (txtConfirmNewPwd.Text == (dr["confirmNewPwd"].ToString()))) { }
}
// MessageBox.Show("Password was changed Successfully!", "Password Change", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You can use ExecuteNonQuery like cmd.ExecuteNonQuery(); It returns int value. Use it like this;
int i = cmd.ExecuteNonQuery();
And also ExecuteReader() works like this;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
You can read returning data's column. Like first column reader[0], second column reader[1] etc.
But before all this information, if you are new to programming, you can find a lot of book proposal and useful informations on Stackoverflow. Check these articles;
What is the single most influential book every programmer should read?
https://stackoverflow.com/questions/477748/what-are-the-best-c-sharp-books
https://stackoverflow.com/questions/2018/best-book-for-a-new-database-developer

Categories