loop in select statment - asp.net

protected void Button1_Click(object sender, EventArgs e)
{
if (firstname_tb.Text == "" || lastname_tb.Text == "" || email_tb.Text == "" || reemail_tb.Text == "" || pass_tb.Text == "" || gender_ddl.SelectedItem.Text == "" || day_ddl.SelectedItem.Text == "" || year_ddl.SelectedItem.Text == "")
{
Label9.Text = "please fill all data";
Label9.Visible = true;
}
else
{
str = email_tb.Text;
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg ",con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
foreach (var v in comsel.Parameters.ToString())
{
if (v.ToString() == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
if (b==true)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
There is a problem that is when I try to enter email allready exist in the database it enterd while it must show to the user that this email already exist in the data base. Can any one help me?

OK as far as I can understand, you only want the INSERT to occur if the email is unique in the [reg].[email] field. This will happen if b == true. The logic you use for this is basically correct, but you are not retrieving the results of the database correctly. Try something like:
con.Open();
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
while (objReader.Read())
{
if ((String)objReader("email") == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
con.Close();
Hopefully that will work as intended.
On a side note, I would be remiss not to mention that this approach is pretty inefficient. A better idea would be to use a query like this:
SELECT [email] FROM [reg] WHERE [email] = #email;
In which you specify your variable "str" as a parameter in a similar manner to the INSERT operation below. Then instead of iterating through the results, simply check to see if the SqlDataReader has any rows:
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT [email] FROM [reg] WHERE [email] = #email;",con);
comsel.Parameters.AddWithValue("#email", str);
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
if (objReader.HasRows())
{
b = false;
}
else
{
b = true;
}
con.Close();

Remove the if statement checking for field entries and add RequiredValidators to your form:
https://web.archive.org/web/20211020145950/https://www.4guysfromrolla.com/webtech/090200-1.shtml
As for the second part.. if email already exists... create a custom validator for this and use this to display the message to your user if the email already exists. Note that you're using ExecuteNonQuery() here for what is essentially a query...
You also need some "separation of concerns". For example, put the connection string in the Web.Config. Do your data access from a DAL class, etc

For the first query, you can just use ExecuteScalar as that will return a single value from your query. I rewrote your query so that it will do a count of the emails that match the email the user is trying to use. If the count returned is 0, then you know that the email is currently not in use.
string strEmail = email_tb.Text.Trim();
try
{
using(SqlConnection conn = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(1) FROM reg WHERE email = #email", conn);
cmd.Parameters.AddWithValue("#email", strEmail);
int count = (int)cmd.ExecuteScalar();
if(count==0)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand cmdInsert = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", conn);
cmdInsert.Parameters.AddWithValue("#fn", firstname_tb.Text);
cmdInsert.Parameters.AddWithValue("#ln", lastname_tb.Text);
cmdInsert.Parameters.AddWithValue("#email", email_tb.Text);
cmdInsert.Parameters.AddWithValue("#reemail", reemail_tb.Text);
cmdInsert.Parameters.AddWithValue("#pass", pass_tb.Text);
cmdInsert.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
cmdInsert.Parameters.AddWithValue("#birth", birthday);
cmdInsert.ExecuteNonQuery();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
}
catch(SqlException ex)
{
// log your exception then display a friendly message to user
Label9.Text = "An error occurred while trying to save your registration";
}

Related

New to ASP and SQL server, How does the condition: IF(dtble.Rows.Count>0) work to match username and password?

Can anyone explain me how does it matches username and password from data table and logs in the user?
DataTable dtForNameAndRole = LoadDataByQuery(sql);
try
{
**if (dtForNameAndRole.Rows.Count > 0)**
{
Session["username"] = dtForNameAndRole.Rows[0]["username"].ToString(); //userID;
Session["password"] = dtForNameAndRole.Rows[0]["password"].ToString(); //userID;
txtpassword.Text = string.Empty;
txtusername.Text = string.Empty;
Response.Redirect("Dashboard.aspx");
Can you please use the below code it'll help you!
using (SqlConnection sqlcon = new SqlConnection(connectionString)){
//string user = txtEmail.Text;
//string pass = txtPassword.Text;
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select count(*) from [dbo].[Register] where Email=#Email and Password=#Password", sqlcon);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", ToSHA2569(txtPassword.Text));
var isCorrectPassword = cmd.ExecuteScalar();
if ((int)isCorrectPassword >= 1)
{
//sqlcon.Close(); //taken care of because of the using command
Response.Redirect("default.aspx");
}
else
{
// sqlcon.Close();
lblWrong.Text = "Password not correct";
}
}

Using datareader to count Asp.net

I'm checking if a barcode from a database table(using a select query) exists and insert the details into another database table else the barcode does not exist. The inserts fine but I would like to count the number of barcodes entered. Say within a session an user enters 5 barcodes then the total count is 5 but my code keeps returning 1 and not incrementing.
protected void btnReturn_Click(object sender, EventArgs e)
{
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectCrate", conn);
SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows) {
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
You can store the number in session then do something with it when the session ends (store it in a database or whatever you want). Declare a session variable:
Session[“NumInserts”] = 0;
Then update it with each insert:
Session[“NumInserts”] = (int) Session[“NumInserts”] + 1;
That variable will be maintained as long as the session exists. Also, make sure you only declare the session variable once and don’t ever allow it to reset during the session’s life cycle. Otherwise, it will go back to 0 and give you inaccurate results.
i rechecked to make sure and i misunderstood your question which led to some confusion.
And to answer your question i don't think there is any easy solution to update realtime the numbers. Any solution of i can think of is websocket connection which I personally have no knowledge of inside webforms(Don't even know if its possible).
I formatted your code. This should give you the total rows back in one go(no realtime update on screen).
protected void btnReturn_Click(object sender, EventArgs e)
{
int counter = 0;
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString()))
{
con.Open();
//commands identifying the stored procedure
using (SqlCommand cmd = new SqlCommand("selectCrate", con))
{
using (SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con))
{
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode;
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter++;
}
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
}
}
}
}

Data Reader and Invalid attempt to read when no data is present

This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !
You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}
If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.

change password in asp.net,c#,ms-access database

i am desiging a change password screen in asp.net,c#,MS-access database
i m having 4 fields
userid,
oldpassword,
newpassword
confirm password
NOW I M NOT GETTING RESULT THE COUNT RETURNS 0 I HAVE UPDATED MY CODE
my code is as follows
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"]
.ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
OleDbDataReader re = cmd.ExecuteReader();
re.Read();
if (re["user_id"].ToString() != String.Empty && re["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch(Exception ex)
{
throw ex;
}
plz help me to solve the error
You're getting the error, No constructor is defined, because you can't directly instantiate this object. As stated on MSDN:
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
Essentially, you'd do something like the following after creating your connection and specifying your query:
OleDbDataReader re = cmd.ExecuteReader();

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Resources