I am a newbie.
I am attempting to check for duplicate database entries. My problem is:
I would like a success alert shown if the entry is successful.
A notification of duplicates shown if a duplicate exists.
My issue is: the alert for duplicates gets shown multiple times, however, the entry is never created if no duplicates exist.
This is my code:
/// <summary>
/// The following procedure creates the user account in the database The procedure first attempts to
/// perform a check for duplicates before submitting the registration info
/// </summary>
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while (CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect, CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while(CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect,CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
Looks like the CheckUser method always returns true and that's why the insertion does not work, update the method to return false by default:
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
return true; // return true if user exists
}
}
CN.Close();
return false; // return false if the user does not exist
It is also recommended to use using block to dispose the DB connection instead of manually invoking the Close() method.
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();
I want to set isLogged to 1 after login, login work but query doesn't work.
Query :
//
public static string loginUpdate = #"UPDATE users SET isLogged = #isLogged WHERE username = #username";
//
public bool userLogin(string userName, string password)
{
SqlConnection conn = db.initializare();
UserModel user = null;
int userId ;
int isLogged = 1;
try
{
cmd = new SqlCommand(Query.loginCheck, conn);
//cmd = new SqlCommand(Query.loginUpdate, conn);
cmd.Parameters.Add(new SqlParameter("username", userName));
cmd.Parameters.Add(new SqlParameter("password", password));
cmd.Parameters.AddWithValue("#isLogged", isLogged);
reader = cmd.ExecuteReader();
while (reader.Read())
{
userName = reader["username"].ToString();
password = reader["password"].ToString();
userId = Int32.Parse(reader["userID"].ToString());
user = new UserModel(userName, password,userId);
if (user != null)
{
cmd = new SqlCommand(Query.loginUpdate, conn);
return true;
}
}
}
catch (Exception ex)
{
var mesajEroare = ex.Message + "-" + ex.InnerException; ;
}
finally
{
conn.Dispose();
conn.Close();
}
return false;
}
You may need to write two separate SqlCommands to perform two operations:
For login check
For login update
Also, always make it a habit to use the using statement when dealing with an object that eats resources such as SqlConnection and SqlCommand. so objects will be automatically disposed after using them.
This will make your code cleaner without explicitly calling the Dispose() call.
Finally, I would suggest you place your SQL operation outside your Button Click event to avoid getting your code more complex. That way it's clean and easy to manage.
To summarize that, here's how your code is going to look like:
private string GetUserPassword(string userName){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "SELECT password FROM users WHERE username = #UserName";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
var result = cmd.ExecuteScalar();
return (result == DBNull.Value) ? string.Empty : result;
}
}
}
private void UpdateLogin(string userName, int isLogged){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "UPDATE users SET isLogged = #isLogged WHERE username = #username";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
cmd.Parameters.AddWithValue("#isLogged", isLogged);
cmd.ExecuteNonQuery();
}
}
}
public bool UserLogin(string userName, string password)
{
string userPassword = GetUserPassword(userName);
if (password.Equals(userPassword)){
UpdateLogin(userName,1);
return true;
}
else{
//username or password is incorrect
}
return false;
}
i have registration page and i want to check that username is already exist in database or not in 3 tier architecture.
MyRegistration.cs:
public static int checkusername(string user_txt)
{
int id2 = 0;
string selectstr = "select * from xyz where UserName = '" + user_txt + " ' ";
id2 = DataAccessLayer.ExecuteReader(selectstr);
return id2;
}
and the code behind onclick event of textbox:
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
int id = xyz.checkusername(txt_username.Text.Trim());
if (id > 0)
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
DataAccessLayer:
public static int ExecuteReader(string Query)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = Query;
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;
}
I have edited some of your codes try like below... it will help you...
Text change Event :
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
if (xyz.checkusername(txt_username.Text.Trim()))
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
Check Username :
public bool CheckUsername(string user_txt)
{
bool Result;
Result = DataAccessLayer.ExecuteReader(user_txt);
return Result;
}
Excute Reader :
public bool ExecuteReader(string user_txt)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("select * from xyz where UserName = #UserID", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserID";
param.Value = user_txt;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
return true;
else
return false;
}
Usually if the "select query" doesn't find a userName with the parameter user_txt you'll id2 will be end up with the value -1. So the appropriate code would be:
if (id ==-1)
{
lblStatus.Text = "UserName Available";
}
if (id>0)
{
lblStatus.Text = "UserName Already Taken";
}
By the way, your code is highly insecure and your database can be easily attacked using SQL Injection I'd recommend you to understand this issue and add parameters to the query to prevent it. C# has its ways to implement this. Don't try to fix the access to the database, just start from scrath keeping in mind SQL Injection.
As others have mentioned, this approach has potentially serious security issues.
However, your problem may lie here user_txt + " ' ". The spaces around the second ', specifically the one before it may lead to the usernames not matching as expected.
Bussiness Access Layer :
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
id = cmd.ExecuteNonQuery();
cmd = null;
con.Close();
return id;
}
Login.cs
protected void Button1_Click(object sender, EventArgs e)
{
int id = BusinessAccessLayer.login(userlogin.Text.Trim(), pwdlogin.Text.Trim());
if (id > 0)
{
message.Text = " valid";
}
else
{
message.Text = "in valid";
}
}
Okay, there are multiple things wrong here:
1) You should use using statements to make sure you close your connection and command even if exceptions are thrown
2) You should use parameterized SQL instead of putting the values directly into your SQL statement, to avoid SQL Injection Attacks
3) You appear to be storing passwords in plain text. Don't do that. Use a salted hash or something similar (ideally something slow to compute).
4) You're ignoring .NET naming conventions; methods should be in PascalCase
5) Your SQL never looks at any field which appears to be related to the user ID. It's not clear what you expect ExecuteNonQuery to return, but if you want the actual ID, you'll need to refer to it in the SQL. (Even if initially you just want to know whether or not the user's password is valid, I strongly suspect that at some point you'll want to user the real user ID, so you should make your code return it. If you really only want to know whether or not the password is valid, you should change the method's return type to bool.)
6) You're using ExecuteNonQuery when your command clearly is a query. Either use ExecuteReader or ExecuteScalar instead. (ExecuteNonQuery is meant for insert, delete and update statements, and it returns you the number of rows affected by the command.)
So something like:
public static int Login(string user, string password)
{
using (var conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
string sql = "select Id, PasswordHash from logins where Username=#Username";
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
using (var reader = command.ExecuteRead())
{
if (reader.Read())
{
int id = reader.GetInt32(0);
string hash = reader.GetString(1);
// TODO: Hash provided password with the same salt and compare
// results
if (CheckPassword(password, hash))
{
return id;
}
}
return 0; // Or use an int? return type and return null
}
}
}
}
The ExecuteNonQuery is used for For UPDATE, INSERT, and DELETE statements.
For SELECT statements, use ExecuteReader
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.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;
}
You can't use .ExecuteNonQuery if you want a result. Use .ExecuteReader.
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserId FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
id = reader.GetInt32("UserId");
reader.Close();
con.Close();
return id;
}