I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.
Related
I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.
This method shows all data from my CarAdd table:
void Bindata()
{
SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.ItemsSource = dt.DefaultView;
}
But, now I need to show the username from the UserAuth table in the dataGridView1 section.
I have tried this code:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
// dataGridView1.ItemsSource = dt.DefaultView;
}
Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:
private void save_Click(object sender, RoutedEventArgs e)
{
if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
{
try
{
con.Open();
string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";
SqlCommand cmd = new SqlCommand(newcon, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully inserted");
Bindata();
// TimeShow();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Invalid credentials");
}
}
Note: I have created a WPF Windows application for this project
Thank you!
Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.
SELECT UserName
FROM UserAuth
So for the Bindatausername() method, the SqlCommand should be changed to the following:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);
i have made a credit request page wherein users can request a value/amount. I have implemented that it should be activated first via email activation before putting the data to the admin page for viewing and approval.
i have made an "Activated" field where it is null until the user has clicked the link on his/her email address and it becomes "1" when user clicks it.
here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = "Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True";
string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString();
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand Activate = new SqlCommand("SELECT UserId FROM CRActivation WHERE ActivationCode = #ActivationCode");
Activate.Parameters.AddWithValue("#ActivationCode", activationCode);
Activate.Connection = con;
con.Open();
string storedUserId = Activate.ExecuteScalar().ToString();
con.Close();
using (SqlCommand cmd = new SqlCommand("DELETE FROM CRActivation WHERE ActivationCode = #ActivationCode"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (rowsAffected == 1)
{
SqlCommand userCmd = new SqlCommand("UPDATE CreditRequests SET Activated = 1 WHERE ID = " + storedUserId);
userCmd.Connection = con;
con.Open();
userCmd.ExecuteNonQuery();
con.Close();
ltMessage.Text = "Credit Request Submitted.";
}
else
{
ltMessage.Text = "Invalid Activation code.";
}
}
}
}
}
what i want to happen is to carry over the "Activated" field and make an if statement that if it is 1, it will be shown in my gridview.
here is the gridview code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IslandGasAdminFM"] != null)
{
bindgrid();
Label1.Text = "- Finance Manager";
}
else
{
Response.Write("<script>alert('Finance Manager credentials needed'); window.location.href='LogIn.aspx';</script>");
}
}
something like this:
if(Activated==1)
{
bindgrid();
}
any help or tricks will be of great help.
SqlConnection con = new SqlConnection(#"Data Source=STRONGLION;Initial Catalog=GIP;Integrated Security=True");
private void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Select count(*) from tblLogin where Gebruikersnaam = '" + txtGebruikersnaam.Text + "' and Paswoord = '" + txtPaswoord.Text + "' and Accounttype'" + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (Accounttype == "1")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
else if (Accounttype == "0")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
}
I have a login form that reads data from a database. What I want is that I can open a form based on what type of user logs in. Above you see a general example how I want it to work.
For example in the database I have 3 things username, password and accounttype, if account type is 1 then its an admin type of account if its 0 then its just a normal account.
Hope someone can help out, thanks in advance!
Your query is wrong, the last part of your WHERE statement is meaningless
"' and Accounttype'" + "'", con);
where is the value for the field Accounttype?
However there is a bigger problem here and is the string concatenation to build your sql text. This could be used to create an Sql Injection attack or it could be simply a source of bugs if your input values cannot be correctly parsed.
You could use a parameterized query as this one
string cmdText = #"Select count(*)
from tblLogin
where Gebruikersnaam = #name and
Paswoord = #pwd and
Accounttype = #type";
and there is no need to build an SqlDataAdapter and a DataTable if you want to get a simple scalar value from your data (the count)
using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtGebruikersnaam.Text;
cmd.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = txtPaswoord.Text;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = Accounttype;
int countType = Convert.ToInt32(cmd.ExecuteScalar());
if(countType == 0)
MessageBox.Show("No user found for the type requested");
else
{
if (Accounttype == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else if (Accounttype == "0")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
}
}
Consider also the advice given in the comments above. You should not store passwords in plain text inside the database. This is a big security risk because everyone that could look at your table could see the password of your users.
Here is my log in page code. What I want to do is when the user inputs his/her username, it will then get all of the database records "based on that username input" of the customer and store it in a single session.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
I have set the Session["Username"] to the user input(txtUser.text), but what I want to do is to get all of the database records on that username that the customer will enter.
Afterwards, I am planning to call on that specific database record and bind it to the order .aspx page. I have tried this code below but its only showing me the Session["Username"], since I have called it on the login page.
txtCustomerName.Text = Session["Username"].ToString();
txtCustomerPhoneNo.Text = Session["Contact"].ToString();
txtCustomerEmailID.Text = Session["Email"].ToString();
txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
You can create a data structure to store the information you need.
public class Person
{
public string Username { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
using (SqlCommand command = new SqlCommand(
"SELECT * FROM databaseTablename where username = " + txtUser.Text, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Person person = new Person();
person.Username = reader.GetString(reader.GetOrdinal("username"));
person.Contact = reader.GetString(reader.GetOrdinal("contact"));
person.Email = reader.GetString(reader.GetOrdinal("email"));
person.Password = reader.GetString(reader.GetOrdinal("password"));
}
}
}
}
You can then store this object in a session like so:
Session["username"] = person;
Later on, if you want to access the contents of the session, say in the Order.aspx page, you can do like so:
Person person = (Person)Session["username"];
get the records from the database. Store it in a comma separated string.
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
SqlDataAdapter da=new SqlDataAdapter(scm);
DataSet ds=new DataSet();
da.Fill(ds);
conn.Close();
string userdata="";
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
userdata+=","+row[i].ToString();
}
}
userdata=userdata.TrimStart(',');
Session["username"]= userdata;
for getting all the records just get this string from session and split it
If(Session["username"]!=null)
String user=Session["username"].ToString();
string[] udat=user.Split(',');
you can get all data in this string array.
Im kind of new to programming so please excuse any error.
This is for storing your all values in single session
DataBaseConnection db = new DataBaseConnection();
DataTable dt = new DataTable();
dt = db.executeNonQuery("Your Query that retrieves all user's data goes here");
if(dt.Rows.Count > 0)
{
List<string> lst = new List<string>();
foreach(DataRow dr in dt.Rows)
{
lst.Add(dr["Cloumn_1"].ToString());
lst.Add(dr["Column_2"].ToString());
.
.
Session["YourSessionName"] = lst;
}
}
here DataBaseConnection is class that returns connection string of database, so now you know what to do.
i hope this helps. Let me know
i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;
I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}