The ConnectionString Property has not been initialised - c#

When I run my code and I input the correct details the first time, the code works perfectly and logs the user in and passes through the id.
However, when I get the details incorrect, and I have to click login again then I get an error:
The ConnectionString property has not been initialised
It gets to the con.Open() and then crashes without opening the database.
Any thoughts?
readonly SqlConnection con = new SqlConnection(#"data source=myPC;initial catalog=cafeDB;trusted_connection=true");
int loginChance = 3;
private void Btn_Login_Click(object sender, EventArgs e)
{
int staffID;
int account;
string user = txt_username.Text;
string pass = txt_password.Text;
using (con) // This will automatically close the connection when the brackets are exited
{
try
{
// THE CODE GETS TO HERE BEFORE BREAKING
con.Open();
// This SQL Command selects the data from the database
using (SqlCommand cmd = new SqlCommand("SELECT username, password FROM tbl_staff WHERE username = #user AND password = #pass", con))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
account = Convert.ToInt32(cmd.ExecuteScalar());
if (loginChance == 0)
{
MessageBox.Show("Your out of login attempts");
}
else
{
if (account == 1)
{
// SQL Statement to get staffID so it can be passed to the other users
using (SqlCommand cmdGetStaffID = new SqlCommand("SELECT staffID FROM tbl_staff WHERE username = #username", con))
{
cmdGetStaffID.Parameters.AddWithValue("#username", user);
staffID = Convert.ToInt32(cmdGetStaffID.ExecuteScalar());
}
var menu = new Main_Menu
{
StaffIDMenu = staffID,
StaffUsernameMenu = user
};
menu.Show();
this.Hide();
}
else
{
loginChance--;
lbl_Incorrect.Text = "Incorrect Username and Password\n" + loginChance + " chance(s) left";
lbl_Incorrect.Show();
this.txt_username.Clear();
this.txt_password.Clear();
}
}
}
}
catch (Exception problem)
{
// This is error checking
MessageBox.Show(problem.Message);
}
}
}

Related

MySql Query does not return any value even though it Exists in the table (C# Asp.net)

I encountered a problem while trying to verify if a value exists in the database. I use Visual Studio 2017.
I wrote a function that checks if Username is in the database table:
protected bool userIsAdmin(string user)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string loginQuery = "select count(*) from AdminTable where User= #Username";
SqlCommand command = new SqlCommand(loginQuery, con);
command.Parameters.AddWithValue("#Username", user);
user = user.Trim();
int rows;
rows = (int)command.ExecuteScalar();
if (rows != 0)
{
OutputLabel.Text = "You are logged";
return true;
}
else
{
OutputLabel.Text = "Try again";
return false;
}
}
I eliminated the probability of an outside error by calling this function like this:
if(userIsAdmin("uia94881"){...}
My database table:
enter image description here
Replace your script as below,
string loginQuery = "select count(*) from AdminTable where [User]= #Username";
because User is a built in function in SQL Server, which will give you the Database username.
SqlConnection connection = new SqlConnection("PUT YOUR CONNECTION STRING HERE");
string loginQuery = "SELECT (User) FROM AdminTable WHERE User = #Username";
SqlDataAdapter adpt = new SqlDataAdapter(loginQuery, connection);
adapt.SelectCommand.Parameters.AddWithValue("#Username", user);
DataSet usr = new DataSet();
adapt.Fill(usr)
foreach(DataRow dr in usr.Tables[0].Rows)
{
string user += usr.Tables[0].Rows[0]["User"].ToString();
}
if(user != "")
{
OutputLabel.Text = "Try again";
return false;
}
else
{
OutputLabel.Text = "You are logged";
return true;
}
Try this instead!

ASP.NET Login in n-tier architecture

I'm trying to implement login functionality in ASP.NET C# based on n-tier architecture.
Data access:
public int userlogin(string user, string passw)//checking the user name and password
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT NurseName, password FROM Nurse2 WHERE NurseName = '" + user.Trim() + "' AND Password = '" + passw.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
Presentation layer .cs file
protected void Button1_Click(object sender, EventArgs e)
{
string name = TextBox1.Text;
string password = TextBox2.Text;
int id = da.userlogin(name, password);
if (id > 0)
{
Session["userName"] = name;
Response.Redirect("SubscribePage.aspx");
}
else
{
Label1.Text = "invalid";
}
Now, my issue is when I press button the program simply goes to else clause, even though I enter correct data. What could be possibly not OK here as to me it all seems fine.
I don't think you need to do that nowadays. ASP.NET has built-in authentication. Just check this out https://msdn.microsoft.com/en-us/library/xdt4thhy(v=vs.140).aspx.
The N-Tier architecture helps separate your code, as it is your code is jumping a layer and does not fully utilizing the business logic layer. Here is a helpful image;
I would also add an additional class to store your users login details, I'm guessing you will have more information along with the nurse name to store - You can store the instance of this class in your session data and cast it out when needed;
public class User
{
public string Name { get; set; }
/* Some other attributes - not your password though! */
}
--
Presentation;
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Session["User"] = BLL.userLogin(TextBox1.Text, TextBox2.Text);
Response.Redirect("SubscribePage.aspx"); /* If it reaches here, everything is okay */
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Business Layer;
public static User userLogin(string username, string password)
{
User U = DAL.userLogin(username, password);
if (string.IsNullOrEmpty(U.Name))
throw new Exception("Incorrect login details");
return U;
}
Data Access Layer;
public static User userLogin(string username, string password)
{
using (SqlConnection con = new SqlConnection(GetConnectionString())
{
User U = new User();
SqlCommand cmd = new SqlCommand(#"SELECT NurseName, password
FROM Nurse2
WHERE NurseName = #user AND password = #pw", con);
cmd.Parameters.Add(new SqlParameter("#user", username));
cmd.Parameters.Add(new SqlParameter("#pw", password));
try
{
con.Open();
}
catch (Exception ex)
{
throw new Exception("connetion problem", ex);
}
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
U = rdr["NurseName"];
}
}
}
catch (Exception ex)
{
throw new Exception("problem with query", ex);
}
finally
{
con.Close(); /* Clean up regardless of the outcome */
con.Dispose();
}
return U;
}
}
Have a read up more into the N-Tier architecture, and try-catch statements. Hope it helps. I would also improve your naming conventions for your controls, to make life easier (ie Label1 -> lblError)

C# Login using MySQL Database - Could not find specified column in results

I am trying to create a login for users which is connected to a MySQL database. When I try logging in on the form I am greeted with the error "could not find specified column in results: password" I have some idea it may be because of my DataReader but unsure how to fix.
public class Security
{
public static string HashSHA256(string value)
{
var sha256 = System.Security.Cryptography.SHA256.Create();
var inputBytes = Encoding.ASCII.GetBytes(value);
var hash = sha256.ComputeHash(inputBytes);
var sb = new StringBuilder();
for (var i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string strConnect = "Server=***.***.***.**;Port=3306;Database=cpr_users;Uid=********;Pwd=********;";
using (MySqlConnection myConn = new MySqlConnection(strConnect))
using (MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = "SELECT COUNT(*) FROM cpr_users.cpr_user_info WHERE username=#User and password=#Password";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
myConn.Open();
MySqlDataReader myReader = selectCommand.ExecuteReader();
var hashedPW = Security.HashSHA256(txtPassword.Text);
var stored = myReader["password"].ToString();
Int32 count = (Int32)selectCommand.ExecuteScalar();
if (count == 1 & hashedPW == stored)
{
MessageBox.Show("Connection Successful");
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am still learning so help is appreciated and if possible an explanation :)
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string strConnect = "Server=***.***.***.**;Port=3306;Database=cpr_users;Uid=********;Pwd=********;";
using (MySqlConnection myConn = new MySqlConnection(strConnect))
using (MySqlCommand selectCommand = new MySqlCommand())
{
var passwordHash = Security.HashSHA256(txtPassword.Text);
selectCommand.CommandText = "SELECT COUNT(*) FROM cpr_users.cpr_user_info WHERE username=#User and password=#Password";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = passwordHash;
myConn.Open();
int count = (int)selectCommand.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Connection Successful");
}
else if (count > 1) // Consider adding a database constraint to prevent duplicate usernames
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}I think you need to call Read() on your MySqlDataReader object
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string strConnect = "Server=***.***.***.**;Port=3306;Database=cpr_users;Uid=********;Pwd=********;";
using (MySqlConnection myConn = new MySqlConnection(strConnect))
using (MySqlCommand selectCommand = new MySqlCommand())
{
// You need to select all the records instead of COUNT(*)
selectCommand.CommandText = "SELECT * FROM cpr_users.cpr_user_info WHERE username=#User and password=#Password";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
myConn.Open();
MySqlDataReader myReader = selectCommand.ExecuteReader();
// If there is a record
if(myReader.Read())
{
var hashedPW = Security.HashSHA256(txtPassword.Text);
var stored = myReader["password"].ToString();
Int32 count = (Int32)selectCommand.ExecuteScalar();
if (count == 1 & hashedPW == stored)
{
MessageBox.Show("Connection Successful");
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Well your select command doesn't return the column password, so you can't read it.
But in reality you don't need to read it back.
Supposing that you store (as you should) the hash of the password, then pass directly the hash.
If you call ExecuteScalar and this method returns not null and > 0 then you are sure that your user has correctly identified itself
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string strConnect = "Server=***.***.***.**;Port=3306;Database=cpr_users;Uid=********;Pwd=********;";
using (MySqlConnection myConn = new MySqlConnection(strConnect))
using (MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = #"SELECT COUNT(*)
FROM cpr_users.cpr_user_info
WHERE username=#User and password=#Password";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text;
selectCommand.Parameters.Add("#Password", MySqlDbType.VarChar).Value = Security.HashSHA256(txtPassword.Text);
object result = selectCommand.ExecuteScalar();
if (result != null)
{
int count = Convert.ToInt32(result);
if(count > 0)
MessageBox.Show("Connection Successful");
else
MessageBox.Show("Incorrect Username and/or Password");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course, you can't have two identical usernames. The field cpr_users.cpr_user_info.username should be defined as an UNIQUE index or as a PRIMARYKEY directly in the datatable schema.
Even if you fix your current code with something like
SELECT * FROM cpr_users.cpr_user_info WHERE username=#user and password=#password
your code will never find the match because you pass the password in clear text when you call the ExecuteReader. This means that, if you find your user then the password is stored in clear text and you cannot compare it with the hashed version returned by Security.HashSHA256. As I have said at the beginning, you should store the HASH not the clear text password.
I am not really sure, but my guess is that you are trying to get a column from a result set where it doesn't exists.
If you run your query with the correct info instead of *****
SELECT COUNT(*) FROM cpr_users.cpr_user_info WHERE username=***** and password=******
you will get a result similar to this:
Count(*)
1
So when you call:
var stored = myReader["password"].ToString();
It's trying to get a Column named 'password' but the only column in your result set is 'Count(*)'.
If you really need the count(*) function you may try:
SELECT password, COUNT(*) FROM cpr_users.cpr_user_info WHERE username=***** and password=****** group by password;
You are not return the "password" field. You are returning just a number, because of the Count(*), that is the number of records that match the criteria.
So, first you retrieve the number of users:
selectCommand.CommandText = "SELECT COUNT(*) FROM cpr_users.cpr_user_info WHERE username=#User";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text;
myConn.Open();
Int32 count = (Int32)selectCommand.ExecuteScalar();
if (count != 1)
//message
After that, you retrieve the password:
selectCommand.CommandText = "SELECT password FROM cpr_users.cpr_user_info WHERE username=#User";
var myReader = selectCommand.ExecuteReader();
if(myReader.Read())
{
var stored = myReader["password"].ToString();
//do the rest of comparison here
}
The question is that a better approach is to ensure that you will NEVER have TWO or more users with the same "user id" in the database. If you ensure that (is the usual) you don't have to check how many users where returned with the "count".
Another point is that is best to send the passord and let the database (via stored proc) to check if the pass is the right one for the user.

How to display the default role for the user at the top of the website? [duplicate]

I have the following database design for an employee table:
Username
Name
Job
etc ..
And a role table:
RoleID
RoleName
Finally, a UserRole table:
UserRoleID
Username
RoleID
I am developing an Intranet web-based application for my department in the company. This application should be accessible only by my department employees and it should the username of the employee with his role (access type) at the top of the website. I have four different roles; Manager, Contribute, Assisstant and User. What I want now is to do the following:
check the user if he is one of the department employees or not.
if not, he will see an error page
if yes, he will be able directly to access the website, and this is his first time in accessing the website, then he should get a User role and this role should be displayed at the top with the username immediately unless the Admin adds him and gives him one of the other roles.
Everything works well and fine except that the used doesn't get the User Role and the role doesn't show at the top if the user is new to the system unless the Admin determines his access in the database
So, how I can give the new user the default role and display it immediately at the top of the website besides his username?
My code-behind is as following:
private bool CheckUsername(string username)
{
if (Service.GetPerson(username).GetProperty("RES_NETID").Equals("-"))
return false;
else if (Security.isPMODMember(username))
return true;
else
return false;
//string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
//string cmdText = "SELECT Count(*) FROM employee WHERE Username = '" + username + "'";
//using (SqlConnection conn = new SqlConnection(connString))
//{
// conn.Open();
// // Open DB connection.
// using (SqlCommand cmd = new SqlCommand(cmdText, conn))
// {
// int count = (int)cmd.ExecuteScalar();
// // True (> 0) when the username exists, false (= 0) when the username does not exist.
// return (count > 0);
// }
//}
}
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
string username = TextBox1.Text;
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
switch (Wizard1.WizardSteps[e.NextStepIndex].ID)
{
case "WizardStep2":
//For checking the user
if (!String.IsNullOrEmpty(username) && CheckUsername(username))
{
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string cmdText = #"SELECT dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo,
ISNULL(dbo.Roles.RoleID, 3) AS RoleID, dbo.Divisions.DivisionName, dbo.Roles.RoleName
FROM dbo.Divisions INNER JOIN dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode
LEFT OUTER JOIN dbo.Roles RIGHT OUTER JOIN dbo.UserRole ON dbo.Roles.RoleID = dbo.UserRole.RoleID ON
dbo.employee.Username = dbo.UserRole.Username
WHERE (dbo.employee.Username = #Username)";
SqlCommand myCommand = new SqlCommand(cmdText, conn);
myCommand.Parameters.AddWithValue("#Username", username);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(table);
ObjectUser user = new ObjectUser(username, true);
string Name = user.Name;
string Username = user.ID;
string DivisionName = user.Org.Title;
string JobTitle = user.GetProperty("EMP_TITLE");
string BadgeNo = user.GetProperty("EMP_BADGE_NUMBER");
string role = "User";
string roleid = "3";
if (table.Rows.Count > 0)
{
role = table.Rows[0]["RoleName"] as string;
roleid = table.Rows[0]["RoleID"].ToString();
}
lblName.Text = Name;
lblUsername.Text = Username;
lblDivision.Text = DivisionName;
lblJobTitle.Text = JobTitle;
lblBadgeNo.Text = BadgeNo;
lblRole.Text = role;
radio1.SelectedValue = roleid;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else
{
//If the user does not exist or a blank value has been entered
//Cancel the nextstep redirection and display an error message in a span
e.Cancel = true;
errorSpan.InnerText = "The username specified is blank or does not belong to PMOD";
}
break;
case "WizardStep3":
break;
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
//If one of the items is selected AND a username exists in the Username session object update the user role
string username = TextBox1.Text;
if (!String.IsNullOrEmpty(radio1.SelectedValue) && !String.IsNullOrEmpty(username))
{
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
//This for adding the new PMOD user to the system
string insertUserCommand = "INSERT INTO employee (Name, Username, JobTitle, BadgeNo, EmpOrgType, DivisionCode) values (#Name, #Username, #JobTitle, #BadgeNo, #EmpOrgType, #DivisionCode)";
string cmdText = "SELECT Count(*) FROM employee WHERE Username = '" + username + "'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
if ((int)cmd.ExecuteScalar() == 0)
{
//An object from ObjectUser class to get the user information from the Secure system and insert them to the database
ObjectUser user = new ObjectUser(username, true);
SqlCommand cmd2 = new SqlCommand(insertUserCommand, conn);
cmd2.Parameters.AddWithValue("#Name", user.Name);
cmd2.Parameters.AddWithValue("#Username", username);
cmd2.Parameters.AddWithValue("#JobTitle", user.GetProperty("EMP_TITLE"));
cmd2.Parameters.AddWithValue("#BadgeNo", user.GetProperty("EMP_BADGE_NUMBER"));
cmd2.Parameters.AddWithValue("#EmpOrgType", user.GetProperty("EMP_EMPTYPE"));
cmd2.Parameters.AddWithValue("#DivisionCode", user.Org.Division.SapCode);
cmd2.ExecuteNonQuery();
}
}
}
//For updating the role of the user by deleting its current role and inserting a new role
string deleteCommand = "DELETE FROM UserRole where Username=#Username";
string insertCommand = "INSERT INTO UserRole (RoleID,Username) values(#RoleID,#Username)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//using (SqlCommand cmd = new SqlCommand(cmdText, conn))
using (SqlCommand cmd = new SqlCommand(deleteCommand, conn))
{
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
//Now the insert
cmd.CommandText = insertCommand;
cmd.Parameters.Clear(); //need this because still has params from del comm
cmd.Parameters.AddWithValue("#RoleID", radio1.SelectedValue);
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
//infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
//cmd.ExecuteScalar();
//infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
}
}
Wizard1.Visible = false;
wizard.InnerHtml = #"<p><b>The task has been done successfully.</b> <br /> <a href='UserManagement.aspx'>Edit Another User</a></p>";
}
}
I think I already did it in Wizard Step#2 as shown above, but it did now work and I don't know why. Any help please?

How to retrieve user information in a placeholder after checking his username in the Wizard?

I am trying to develop a simple user management system for the admin of the web application. I am using ASP.NET Wizard Control for this task.
I just put a TextBox for writing the username and when the admin clicks on the Next button, the system should check if the username existed in the database or not. If it is existed, the system should display his information in a placeholder for the admin.
I am struggling with this task. I did the following in the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
//Session["Username"] = Username.Text;
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=testdb;Integrated Security=True";
string cmdText = "SELECT * FROM employee WHERE Username = #Username";
//For checking the user
if (Request.QueryString["Username"] != null)
{
String strUserName = Request.QueryString["Username"];
////Check userName Here
//String strReturnStatus = "false";
if (CheckUsername(Request.QueryString["Username"]) == true)
{
//strReturnStatus = "true";
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(cmdText, conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["Name"].ToString());
Console.WriteLine(myReader["Job"].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
//Response.Clear();
//Response.Write(strReturnStatus);
//Response.End();
}
}
private bool CheckUsername(string username)
{
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=testdb;Integrated Security=True";
string cmdText = "SELECT * FROM employee WHERE Username = '" + username + "'";
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); // Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
int count = (int)cmd.ExecuteScalar();
// True (> 0) when the username exists, false (= 0) when the username does not exist.
return (count > 0);
}
}
}
I tried to test this by writing any username in the TextBox, but I did not get any result when I clicked on Next button of the wizard that should redirect me to the placeholder or any control that should display the user information. What I want now is just showing the information of the user if his username existed in the database. How to do that?
First of all you need to understand the concept of page load and postbacks. The code written inside Page_Load will execute every time the page is loaded either by entering the URL in browser or by becuase of button click event. You should place the code that you want to execute only once in
if(!isPostback)
{
//code to be need to be executed for the first time
//only goes within this block
}
Then as Asken suggested have a look at SQL injection too
Now regarding the problem, in your Page_Load event you have:
string cmdText = "SELECT * FROM employee WHERE Username = #Username";
You need to set the value of #Username parameter and this is how you can do this:
myCommand.Parameters.Add("#Username", SqlDbType.VarChar, 30); //assumption: UserName column is of varchar type length of 30
nonqueryCommand.Parameters["#Username"].Value = strUserName;

Categories

Resources