I am planning to check the username based on user input from the text box and I am planning to have the error message immediately after putting the existing username. for now i have this code. I am not experiencing errors but its not working. what am i missing here?
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"] = txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
protected void txtUser_TextChanged(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDAta where Username='" + txtUser.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Imagemessage.Visible = true;
lblusercheck.Visible = true;
Imagemessage.ImageUrl = "NotAvailable.jpg";
lblusercheck.Text = "Username already exists.";
}
else
{
Imagemessage.Visible = true;
lblusercheck.Visible = true;
Imagemessage.ImageUrl = "Available.gif";
lblusercheck.Text = "You can choose this username.";
}
}
}
TextChange Event would not be called upon any single key press. What you should do is to use javascript to create a postback to the server (for example using __doPostBack) in the client side function keyup
Also, this would be a postback and you should not check for !isPostBack in the Handler.
Update:
Markup:
<asp:TextBox runat="server" ID="txt" onkeyup="check(this);" />
Javascript
function check(txt) {
__doPostBack('Control to Update', 'Filter--'+txt.value);
}
codebehind:
form_load:
parameter = Request["__EVENTARGUMENT"];
if (parameter != null && parameter.startsWith("Filter--"))
{
//Do your check here.
}
I don't like this kind of coding as it is messy.
Related
I always get the "else", even though I add the correct username and password
Photo with the script
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CONSTRing);
con.Open();
string q = "select * from LOGG where username = '" + tbu.Text + "' and password = '" + tbp.Text + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
Da.Fill(DT);
if (DT.Rows.Count == 1)
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
}
Photo with dbo.LOGG
I will try to be helpful with an answer since I can't yet comment ;_;
Below is some code I compiled as an improvement to the one you posted.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string q = "select 1 from LOGG where username = #username and password = #password";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#username", tbu.Text); //
cmd.Parameters.AddWithValue("#password", tbp.Text); // using parameters to avoid intentional or accidental SqlInjection by the user
using (SqlDataReader reader = cmd.ExecuteReader())
{
try
{
con.Open();
if (reader.Read())
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
cmd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Oops something went wrong. Error: " + ex.Message);
}
}
}
This is how I would write a quick version of what you wanted. Now, it might not help you out with your issue but it fixes some of the more obvious issues that might come up.
The Try and Catch block are there just for basic error handling to let the user know something went wrong.
The SqlDataReader is enough to notify you if a user with the given parameters exists in the database.
The check you used before
if (Dt.Rows.Count == 1)
{
//...
}
would fail to trigger if your query returned more than 1 row, which should not happen if the Table is created correctly. Check for duplicate entries in your table.
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
lblMessage.Text = "Invalid login credentials";
}
else
{
Response.Redirect("SubmitViewingRequest.aspx");
}
}
the codes above doesn't validate the email address and password with the database. any email address and password entered is considered correct. can i get help? thank you!
Change your if condition
if (result.Tables["Login"].Rows.Count > 0) // For Successfully Login
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else // For Invalid User credentials
{
lblMessage.Text = "Invalid login credentials";
}
This happens when we mistakenly put if conditions in reverse order. Please change your code with if conditions replaced like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
string EmailAddr = "";
string Password = "";
string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=#EmailAddr AND [Password]=#Password", conn);
cmd.Parameters.AddWithValue("#EmailAddr", EmailAddr);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
daParentLogin.Fill(result, "Login");
conn.Close();
if (result.Tables["Login"].Rows.Count > 0)
{
Response.Redirect("SubmitViewingRequest.aspx");
}
else
{
lblMessage.Text = "Invalid login credentials";
}
}
Hope this helps
I have created 2 DropDownLists First dropdown contains "TeamName" and second one contain "TeamMember" name. The requirement is when we select particular TeamName from dropdown second dropdown should automatic populates the team member name and after button click data should be inserted in database,It works fine for first button click but second time on the same page "TeamName" dropdown does not show name of department,suddenly it gets lost.So Please suggest me what I need to do to resolve this issue??
Following is the code which I did to achieve this task
User.aspx page code:
User.aspx.cs page code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTeamName();
txtCurrentDate.Text = DateTime.Now.ToString("MM-dd-yyyy");
txtCurrentDate.ForeColor = System.Drawing.Color.Green;
}
}
private void BindTeamName()
{
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamName", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl1.DataSource = ds;
ddl1.DataTextField = "TeamName";
ddl1.DataValueField = "TeamId";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
int TeamId = Convert.ToInt32(ddl1.SelectedValue);
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamResource where TeamId=" + TeamId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl2.DataSource = ds;
ddl2.DataTextField = "EmpName";
ddl2.DataValueField = "EmpId";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(SqlString))
{
SqlCommand cmd = new SqlCommand("InsertUserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#WorkDate", txtCurrentDate.Text);
cmd.Parameters.AddWithValue("#TeamName", ddl1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#TeamMember", ddl2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AvailableBandwidth", ddlAvailable.SelectedItem.Value);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
}
}
I would re-bind the "TeamName" dropdown list after a successful save.
//btnSubmit_Click
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
BindTeamName(); //re-bind the initial dropdown so you can select a new team
}
Actually you can use that method either way, depending on what ClearFields() does.
I want to check if a username is already in the database. It comes along with my update statement. I have this code and I do not know where to put the select statement:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "update UserData set Password=#Password where UserName='" + txtUser.Text + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text);
com.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
con.Close();
}
I want something like
"Select Username from Userdata Where Username = txtUser.Text"
You don't need a SELECT here. ExecuteNonQuery() returns the number of rows affected, which means that when it returns 0, there was no user with the given name in the database. If all went well, it should return 1.
Your code is vulnerable to SQL injection and leaks resources. Here's a better version:
protected void btn_update_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(conn))
{
con.Open();
var commandTest = "update UserData set Password=#Password where UserName=#Username";
using(var com = new SqlCommand(commandTest, con))
{
com.Parameters.AddWithValue("#Username", txtUser.Text);
com.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
if(com.ExecuteNonQuery() == 1)
{
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
}
}
}
}
I have two textboxes and two buttons on one site. The problem is that this second textbox and second button doesn't work. First textbox+button doing well:
int NoOfDigTextBoxEngine;
protected void TextBoxADDEngine_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxEngine = TextBoxADDEngine.Text.Length;
}
protected void ButtonADDEngine_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Engine, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsEngine";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxEngine == 7)
{
try
{
Convert.ToInt32(TextBoxADDEngine.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsEngine ([Engine], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDEngine.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView3.DataBind();
TextBoxADDEngine.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika może zawierać jedynie cyfry.')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika musi mieć 7 cyfr.Podano: " + NoOfDigTextBoxEngine + " ')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
}
}
But the second (is the same) don't want to work.
int NoOfDigTextBoxGear;
protected void TextBoxADDGear_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxGear = TextBoxADDGear.Text.Length;
}
protected void ButtonADDGear_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Gear, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsGear";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxGear == 7)
{
try
{
Convert.ToInt32(TextBoxADDGear.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsGear ([Gear], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDGear.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView5.DataBind();
TextBoxADDGear.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni może zawierać jedynie cyfry.')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni musi mieć 7 cyfr. Podano: "+ NoOfDigTextBoxGear +" ')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
}
}
When i write something in second textbox and then click button- always NoOfDigTextBoxGear = 0...why?
It's not make any sense for me because this code(for second textbox and button) is the same like the the first one(for first textbox and button).
Oh... i just saw this:
<asp:TextBox ID="TextBoxADDGear" runat="server" Visible="False"
Width="96px"></asp:TextBox>
I didn't add ontextchanged(!)
ontextchanged="TextBoxADDGear_TextChanged"
Now everything is ok.