I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}
Related
I have below data in SQL query, and am showing the current user "Domain" logged in I want to show the full name in label based on each user using the Windows form,
I got stuck here, how I can continue to find the value
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
label1.Text = userName.ToUpper();
SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=db;User ID=AAA;password=******");
con.Open();
string command7 = "SELECT distinct [fullname] ,[Group] ,[Domain] FROM [tableA] where fullname is not null and [group] is not null and [Domian] = '"+ label1.Text + "'";
SqlCommand da7 = new SqlCommand(command7, con);
Full name
Group
Domain
Alex Sam J
A GROUP
test\Alex
Jon Pete F
B GROUP
test\Jon
You can get the value of full name this way :
...
SqlCommand cmd = new SqlCommand(command7, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
labelFullName.Text = da.Tables[0].Rows[0]["fullname"].ToString();
I solve it like this, thanks
SqlCommand cmd = new SqlCommand(da7, con);
cmd.CommandType = CommandType.Text;
//con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//DataTable dt7 = new DataTable();
while (reader.Read())
{
label21.Text = reader["Technician"].ToString();
}
con.Close();
These are the tables in my project:
I am trying to update a DataGridView so that it displays the data of the user who is logged in.
I am getting the error: 'Must declare scalar variable '#CurrentUserID'... I think this is because I cannot convert the value to an int but if this is the case how do I fix the problem?
This is my code so far:
//Find ID of user who is logged in
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True");
SqlCommand command = new SqlCommand("select UserID from Users where Username = '"+loggedInLabel.Text+"' ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int currentUserID = reader.GetInt32(reader.GetOrdinal("UserID"));
command.Parameters.Add("#CurrentUserID", SqlDbType.Int);
command.Parameters["#CurrentUserID"].Value = currentUserID;
//update datagridview
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #CurrentUserID";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
dataGridView.DataSource = ds;
dataGridView.DataMember = "Records";
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Just in case anyone else was stuck with it.
I solved it by removed the code where I added the parameters and replacing it with :
dataadapter.SelectCommand.Parameters.AddWithValue("#CurrentUserID", currentUserID);
Thanks for the help!
You have many errors in your code, you're not disposing anything and re-using the command in a invalid way (while the reader is executing).
You're not using parameters. You're not re-using the SQL Connection. You're not adding parameters in the correct way.
This is how the code should look
try
{
DataSet records = new DataSet();
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True"))
{
int? userId = null;
using (SqlCommand command = new SqlCommand("select UserID from Users where Username = #Username", conn))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = loggedInLabel.Text;
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
if (reader.Read())
userId = reader.GetInt32(reader.GetOrdinal("UserID"));
conn.Close();
}
if (userId == null) // No row found
throw new ApplicationException("User not found");
using (SqlCommand command = new SqlCommand("select * from Records where UserID = #CurrentUserID", conn))
{
command.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = userID.Value;
// SqlDataAdapter opens and closes the connection itself.
using (SqlDataAdapter dataadapter = new SqlDataAdapter(command))
dataadapter.Fill(records , "Records");
}
}
//update datagridview
dataGridView.DataSource = records ;
dataGridView.DataMember = "Records";
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
You should also combine SQL Queries
select UserID from Users where Username = #Username and select * from Records where UserID = #CurrentUserID can be combined into this:
select Records.*
from Records
join Users
on Users.UserID = Records.UserID
where Users.Username = #Username
Then you only have to supply the Username and you'll get the records if everything is there.
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
I'm making an asp.net application, I'm trying to read data from sql tables, but data just wont compare, as I don't get the message "You don't have a bank account, you can't register to our website"
SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True");
connection.Open();
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber='" + accountnumber1.Text + "'", connection);
reader = command.ExecuteReader();
if (reader.Read())
{
string getAccountNumber = reader[0].ToString();
reader.Close();
if (getAccountNumber != accountnumber1.Text)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
The best way to find this issue is to put a break point on the line:
if (getAccountNumber != accountnumber1.Text)
and see why the values do not match.
My guess is that account number is not the first column in your SELECT * query, thus reader[0].ToString() is not really the account number, but another value. Instead get the column index via the column name, like this:
string getAccountNumber = reader.GetString(reader.GetOrdinal("Accountnumber"));
It would also be a great idea to use a parameterized query so you do not get a visit from Little Bobby Tables.
Here is your code using a parameterized query:
string theQuery = "SELECT * FROM ACCOUNTS WHERE Accountnumber=#AccountNumber";
SqlCommand command = new SqlCommand(theQuery, connection);
command.Parameters.AddWithValue("#AccountNumber", accountnumber1.Text);
reader = command.ExecuteReader();
I would check reader.HasRows property and show the message
using (SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber= #Accountnumber", connection))
{
command.Parameters.AddWithValue("Accountnumber", accountnumber1.Text);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
if (!reader.HasRows)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
}
I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?
"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects