login page asp.net sql - asp.net

I have this code and need to complete it..
string conn_str =
#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf;
Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(conn_str);
SqlCommand cmd = new SqlCommand("SELECT Password FROM Users WHERE UserName=#un", conn);
cmd.Parameters.Add("#un", SqlDbType.NVarChar);
cmd.Parameters["#un"].Value = **???**;
conn.Open();
string pwd = (string)cmd.ExecuteScalar();
conn.Close();
I have some values in sql data:
Tables:
Users
Username
Password
Now in login page i have textboxNAME and textboxPassword and if user type right login info(that in database) it refers him to default.aspx

Try
cmd.Parameters["#un"].Value = textboxName.Text;
and
if(textboxPassword.Text.Equals(pwd))
{
Request.Redirect("default.aspx");
}
else
{
//login failed
}

Try This:
string conn_str = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydb.mdf; Integrated Security=True;User Instance=True";
private string _password;
SqlConnection conn = new SqlConnection(conn_str);
SqlCommand cmd = new SqlCommand("SELECT Password FROM Users WHERE UserName=#un", conn);
cmd.Parameters.Add("#un", SqlDbType.NVarChar,50).Value=txtusername.text;
//use add with value to specify which object you want to use
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//load data to datatable
DataTable dt = new Datatable();
conn.Open();
adapt.Fill(dt);
//get Password on Datatable
Foreach(DataRow a in dt.Rows)
{
_password = a["Password"].Tostring();
}
//Check password
if(_password==string.Empty)
{
//remain
}
else if(_password==txtpassword.Text)
{
Response.Redirect("My page");
}
conn.Close();
Regards

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";
}
}

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

where to add connection string of SQL server in asp.net page

I am having an ASP.NET page that is containing the textboxes namely username and password and a button named cmdlogin. I want that when I enter the data in text boxes then that data should be saved into the database.
In SQL server of Visual studio, I have created table and even also have given the
INSERT INTO cmd_login VALUES(".......").
Now the problem is when I entered the data in textbooxes it is not saved in the database table. what can I do.
I have put my connection string into the class file. Do I need to put my connection string in the web.config?
my code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
public class Db
{
public static SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString =#"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\talat\MyRealSacaProject\App_Data\SACALogin.mdf;Inte grated Security=True;User Instance=True;";
cn.Open();
return cn;
}
public static void SaveAdmin(admin a)
{
SqlConnection cn = GetConnection();
string sql = "INSERT INTO admin_login VALUES(#[User-Name],#Password)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("#[User-Name]",a.username);
cmd.Parameters.AddWithValue("#Password", a.password);
cmd.ExecuteNonQuery();
cn.Close();
}
}
try this simple code:
SqlConnection _conn = new SqlConnection(_connString);
_conn.Open();
SqlCommand _cmd = new SqlCommand();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Clear();
_cmd.Connection = _conn;
_cmd.CommandText = "INSERT INTO [tablename] VALUE ([fieldvalue])"; //here your textbox
int _execute = _cmd.ExecuteNonQuery();
bool _result = false;
if(_execute != 1)
_result = true;
_conn.Close();
chnage your code as given below, it will work
public static SqlConnection GetConnection()
{
string ConString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\talat\MyRealSacaProject\App_Data\SACALogin.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(ConString);
cn.Open();
return cn;
}
try this change from your code :
public static void SaveAdmin(admin a)
{
SqlConnection cn = GetConnection();
string sql = "INSERT INTO admin_login VALUES('" + a.username + "','" + a.Password + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.ExecuteNonQuery();
cn.Close();
}

asp.net login web page using sql server

i am stuck in my login page..my button click event is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
string cs = "Data Source=ims-aab46237892;Initial Catalog=Inventory;Integrated Security=True";
string SelectString = "SELECT COUNT(*) FROM user WHERE username = #Username AND password = #Password";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(SelectString,con);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelectString;
SqlParameter username = new SqlParameter("#Username",SqlDbType.VarChar,50);
username.Value = TextName.Text.Trim().ToString();
cmd.Parameters.Add(username);
SqlParameter password = new SqlParameter("#Password", SqlDbType.VarChar, 50);
password.Value = TextPass.Text.Trim().ToString();
cmd.Parameters.Add(password);
con.Open();
if(cmd.ExecuteScalar() != null)
Response.Redirect("Home.aspx");
else
Response.Redirect("wrongpasspage.aspx");
con.Close();
}
and my data table has the required username and password fields.. error i am getting is incorrect syntax near keyword user... plz help
user is a reserved keyword in SQL server. Try [user] or rename your table to Users.
use [user] instead of user in SelectString statement.

Can't Get value from database in ASP.net

Hi can you help me with this??
I have this code and i want to display the result of my query into my 3rd Textbox but it not displaying.
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = '" + TextBox2.Text + "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
But then i just use this query without the where condition i can see the output;
string query = "SELECT UserID FROM [IBSI].[sec].[Users]";
Thanks in advance
I'd recommend using parameterized queries for this task. Also, generating sql code from user input (like text boxes/memos) is prone to sql injections (user may enter any sql code into the textbox that may damage database data), so it'd be great to validate input data.
Sample parameter usage is like this:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = #1";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlParameter p1 = new SqlParameter("#1", TextBox2.Text);
cmd.Parameters.Add(p1);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
Step through the debugger and verify that your query is returning results.
ey Bert change in your code as follows:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName= '"+TextBox2.Text+ "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
int UserId;
UserId=Convert.ToInt32(cmd.ExecuteScalar());
TextBox3.Text=UserId.ToString() ;
}
}
}

Resources