My output on SQL query is not viewing on my textbox, when the form load it must be automatically inserted to my textbox. The only output on my textbox is System.Data.SqlClient.SqlCommand
I don't know whats wrong or missing on my codes. Please help me, sorry I'm just a newbie on c#
Any type of response is greatly appreciated. Thank you in advance.
private void EmailGen_Load(object sender, EventArgs e)
{
connect.Open();
string emailto = "select emailaddress from emails where password = ''";
string emailfr = "select emailaddress from emails where password != null";
SqlCommand emailt = new SqlCommand(emailto, connect);
SqlCommand emailf = new SqlCommand(emailfr, connect);
emailt.ExecuteNonQuery();
txBEmailRec.Text = emailt.ToString();
txBEmailFr.Text = emailf.ToString(); ;
connect.Close();
// TODO: This line of code loads data into the 'kwemDataSet.tblProducts' table. You can move, or remove it, as needed.
this.tblProductsTableAdapter.Fill(this.kwemDataSet.tblProducts);
}
You should use ExecuteScalar(); instead of ExecuteNonQuery(); And also, you code seems to missing to execute emailf SqlCommand.
You could see this reference as well.
private void EmailGen_Load(object sender, EventArgs e)
{
connect.Open();
string emailto = "select emailaddress from emails where password = ''";
string emailfr = "select emailaddress from emails where password != null";
SqlCommand emailt = new SqlCommand(emailto, connect);
SqlCommand emailf = new SqlCommand(emailfr, connect);
txBEmailRec.Text = emailt.ExecuteScalar().ToString();
txBEmailFr.Text = emailf.ExecuteScalar().ToString();
connect.Close();
// TODO: This line of code loads data into the 'kwemDataSet.tblProducts' table. You can move, or remove it, as needed.
this.tblProductsTableAdapter.Fill(this.kwemDataSet.tblProducts);
}
Related
I'm trying to get my LoginButton to work, it isn't really doing what I want it to do.
I already have a RegisterButton which works perfectly and creates the account without any problems, but when trying to do my LoginButton it connects to the database but doesn't really check if the account exists using selectQuery and it should change WarningLabel.Text to "Wrong Name or Password". it does go through the first try and changes the WarningLabel.Text to "Welcome " + NameInput.Text;
private void LoginButton_Click(object sender, System.EventArgs e)
{
string selectQuery = $"SELECT * FROM bank.user WHERE Name='{NameInput.Text}' AND Password='{GetHashString(PasswordInput.Text)}';";
MySqlCommand cmd;
connection.Open();
cmd = new MySqlCommand(selectQuery, connection);
try
{
cmd.ExecuteNonQuery();
WarningLabel.Text = "Welcome " + NameInput.Text;
} catch
{
WarningLabel.Text = "Wrong Name or Password";
}
connection.Close();
}
Best Regards - Nebula.exe
The ExecuteNonQuery is not intented to be used with SQL statements that return data, you should use ExecuteReader or ExecuteScalar, you can check the MySqlCommand.ExecuteReader documentation
Warning: Your code does have a SQL Injection vulnerability in this part of the SQL statement Name='{NameInput.Text}' Check this SQL Injection explanation
Usage example (from the documentation, slightly modified):
using (MySqlConnection myConnection = new MySqlConnection(connStr))
{
using (MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection))
{
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
}
}
You should check if there are records returned. cmd.ExecuteNonQuery(); won't tell you if records are returned because it will just execute the query. You should use ExecuteScalar or a MySQL Data Reader ExecuteReader and track the results.
Note : Your code is prone to SQL Injections, you might want to use Parameters in your query like #name and #password.
Your Query goes something like this.
string selectQuery = $"SELECT IFNULL(COUNT(*),0) FROM bank.user WHERE Name=#name AND Password=#password;";
Then use parameters
cmd.parameters.AddWithValue(#name, NameInput.Text);
cmd.parameters.AddWithValue(#password, GetHashString(PasswordInput.Text));
Then verify if the query returns result
If cmd.ExecuteScalar() > 0
//If count is > 0 then Welcome
//Else Wrong username or password
End If
Your life, made easy:
private void LoginButton_Click(object sender, System.EventArgs e)
{
var cmd = "SELECT * FROM bank.user WHERE Name=#name AND Password=#pw";
using var da = new MySqlDataAdapter(cmd, connection);
da.SelectCommand.Parameters.AddWithValue("#name", NameInput.Text);
da.SelectCommand.Parameters.AddWithValue("#pw",GetHashString(PasswordInput.Text));
var dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count == 0)
WarningLabel.Text = "Wrong Name or Password";
else
WarningLabel.Text = $"Welcome {dt.Rows[0]["FullName"]}, your last login was at {dt.Rows[0]["LastLoginDate"]}";
}
Your life, made easier (with Dapper):
class User{
public string Name {get;set;} //username e.g. fluffybunny666
public string FullName {get;set;} //like John Smith
public string Password {get;set;} //hashed
public DateTime LastLoginDate {get;set;}
}
//or you could use a record for less finger wear
record User(string Name, string FullName, string Password, DateTime LastLoginDate);
...
using var c = new MySqlConnection(connection):
var u = await c.QuerySingleOrDefaultAsync(
"SELECT * FROM bank.user WHERE Name=#N AND Password=#P",
new { N = NameInput.Text, P = GetHashString(PasswordInput.Text)}
);
if(u == default)
WarningLabel.Text = "Wrong Name or Password";
else
WarningLabel.Text = $"Welcome {u.FullName}, your last login was at u.LastLoginDate";
I Retrive values from admin table and then i store in String variable and finally i compare values my code is not redirect to another page
protected void Button1_Click(object sender, EventArgs e)
{
String uname = (String)txtuser.Text;
String upass = (String)txtp.Text;
String cuser = "";
String cpass = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HMSS"].ToString());
conn.Open();
String query = "select username,password from admin where username=#username";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("username", uname);
cmd.Parameters.AddWithValue("password", upass);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cuser = rdr["username"].ToString();
cpass = rdr["password"].ToString();
}
if (cuser==uname && cpass==upass)
{
Session["user"] = cuser;
Response.Redirect("admin.aspx",true);
}
}
}
Can you check following code lines?
String uname = (String)txtuser.Text;
(string) implicit cast is not necessary: Text property is already a string.
conn.Open();
missing conn.Close(); it's better to add also try/catch
String query = "select username,password from admin where username=#username";
cmd.Parameters.AddWithValue("password", upass);
why don't you check also password in the query?
cuser = rdr["username"].ToString();
It means null value not allowed
if (cuser==uname && cpass==upass)
Problem with case sensitive/trim. In debug do you arrive on Response.Redirect?
Response.Redirect("admin.aspx",true);
Maybe ~/admin.aspx
try to change your condition to below
if (cuser.ToLower() == uname.ToLower() && cpass.ToLower() == upass.ToLower())
How do I link textboxes?
Scenario:
TextBox_Supplier
TextBox_Address
TextBox_Supplier is autocomplete and it's working. When typing is done in TextBox_Supplier, the TextBox_Address will select supplier's address.
My code does not work:
private void txb_vendor_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txb_address.Text))
{
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon.getcon();
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name = {0}",txb_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
address = txb_address.Text;
}
PurCon.con.Close();
}
}
Thank you for helping me!
instead of
address = txb_address.Text;
write
txb_address.Text = address;
Try to use Parameterized Query instead of concatenation of the strings.
Do Change as #Mohit suggested and also wrap the supplier name with single quotes, since supplier name is string type and in sql String should be wrap in single Quotes other wise this will give SQL Error
"SELECT address FROM tbl_Supplier WHERE supplier_name = '{0}'"
----^
I already solved this problem last week. And I'm so angry to myself!
The textbox_Address does not changed once, it stacks up when the textbox_Supplier_TextChaged. So I put Clear() method to clear previous input address.
public void AddressTbxLoad()
{
DBCon PurCon = new DBCon();
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon2.con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name LIKE '{0}%'", cbx_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
txb_address.Text = address;
}
PurCon.con.Close();
}
private void cbx_vendor_SelectedIndexChanged(object sender, EventArgs e)
{
txb_address.Clear();
AddressTbxLoad();
}
private void Purchase_Load(object sender, EventArgs e)
{
VendorTbxLoad();
}
On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);
i've been struggling to understand how to validate data i entered in an input in an .aspx webform,
say username and password, i've tried many things, tried reading about it and looking for solutions but all of them are really messy with a lot of things i don't really need.
It is for a school project in my school and i already set up a working database, and i already made a register page, that works and it submits it to the database.
Our teachers supplied us with a DalAccess file, that is stored in the App_Data folder in my project.
This is the code inside of it:
public class DalAccess
{
private OleDbConnection conn;
private OleDbCommand command;
private OleDbDataAdapter adapter;
public DalAccess(string strQuery)
{
string ConnectionString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb");
conn = new OleDbConnection(ConnectionString);
command = new OleDbCommand(strQuery, conn);
adapter = new OleDbDataAdapter(command);
}
public DataSet GetDataSet(string strSql)
{
DataSet ds = new DataSet();
command.CommandText = strSql;
adapter.SelectCommand = command;
adapter.Fill(ds);
return ds;
}
public int InsertUpdateDelete(string strSql)
{
int rowsAffected;
this.conn.Open();
OleDbCommand cmd = new OleDbCommand(strSql, conn);
rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
return rowsAffected;
}
}
Note: i am a complete beginner and have no idea what does anything in that code means.
So, i wrote these lines of code in the aspx.cs page behind
{
public DataSet ds ;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
string loginid = Request.Form["loginid"];
string loginpw = Request.Form["loginpw"];
string sqlS = "Select IDD,Pass from UserInfo where IDD = '"+ loginid + "'";
DalAccess dal = new DalAccess(sqlS);
ds = dal.GetDataSet(sqlS);
}
}
}
And if i wrote it correctly i selected the two tabs of the row that the value of IDD(ID of the user) in the table is loginid.
Problem is, i can't figure out how to take that data i selected and compare it to the things entered into the inputs and to check if they match.
I'd greatly appreciate if someone were to go as far as explain to me what everything does, since my teacher hasn't got a lot of time to give to all the students, but an example and a simple explanation will work for me too.
Important note!: I know if i make it parameterized it is safe against sql injection, which i did not do, but this part of the project is not for the purpose of security, which we will have a part for it too, and we will learn.
Thanks in advance.
when water rises above the level of the noses, only those will survive, who know how to swim, isn’t it?
Technically we will go for stored procedure to validate the login[as best practices].In the link the its very clear that you can do it with minimal coding.
How to validate login and pass userID
Updated:
ok, if we want to do it in your way.
In the code behind inside the method
private void ValidateLogin()
{
string uname = "Hsakarp";//I have hard-coded the value to make it simple
string pwd = "12345";
string sqlS = "Select UserName,Password from Login where UserName = '" + uname + "' and Password = " + pwd;
DalAccess dal = new DalAccess();
DataSet ds = dal.GetDataSet(sqlS); //GetDataset is gonna return the ds
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["UserName"].ToString().Trim() == uname && ds.Tables[0].Rows[i]["Password"].ToString().Trim() == pwd)
//Check whether the username and password exists.
Label1.Text = "Login Successfull";
else
Label1.Text = "Login failed";
}
}