This code shows me that "CommandText has not been initialized" - c#

I want to check ManagerUsername and ManagerEmail in the database and the display a messagebox to show the user with their password.But when I execute the code it shows me that:
"commandtext has not been initialized"
so I want to know how can I fix my code to display what I want. And also a way to improve my code to work more efficient
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Cybertronics
{
public partial class passwordRecovery : Form
{
int pin = 0;
private int _failedAttempts = 0;
public passwordRecovery()
{
InitializeComponent();
}
private void passwordRecovery_Load(object sender, EventArgs e)
{
lblAttempt.Visible = false;
}
private void btnBackLogin_Click(object sender, EventArgs e)
{
loginFrm loginForm = new loginFrm();
this.Hide();
loginForm.Show();
}
private void btnSubmitEmail_Click(object sender, EventArgs e)
{
try
{
string emailAddress = txtEmail.Text;
string username = txtManagerUsername.Text;
string password = "ChangeMe";
CyberDatabase db = new CyberDatabase();
db.OpenConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Parameters.AddWithValue("#ManagerUsername", username);
cmd.Parameters.AddWithValue("#ManagerEmail", emailAddress);
db.SetSqlCommand(cmd);
reader = db.Select();
cmd.CommandText = "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail";
db.SetSqlCommand(cmd);
reader = db.Select();
if (reader.HasRows)
{
reader.Read();
SqlCommand passwordUpdate = new SqlCommand();
passwordUpdate.CommandText = "UPDATE tblManagers SET ManagerPassword=#Password WHERE ManagerUsername=#ManagerUsername and ManagerEmail=#ManagerEmail";
db.SetSqlCommand(passwordUpdate);
MessageBox.Show("your new password is:" + password);
}
else
{
if (pin != 21)
{
_failedAttempts++;
MessageBox.Show("Wrong password or username fail to login. you have" + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
if (_failedAttempts == 3)
{
Application.Exit();
}
}
}
}
catch (SqlException sql)
{
CyberMethods.DisplayErrorMessage(sql.Message);//error message from cybermethods class for DB
}
catch (Exception exc)
{
CyberMethods.DisplayErrorMessage(exc.Message);//error message from cybermethods class
}
}
}
}

your code is very messy and untidy. It is very error prone. Check the below sample code for best practices.
using (connection)
using (SqlCommand command = new SqlCommand(
"SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail",
connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
}
}
you have multiple query statements. for the seperation of duties principles I suggest you to make 3 functions each seperate and call them respectively.
and It is wise to keep connection open then then close when all the operations finish.
For solving your error
before your first db.SetSqlCommand(cmd); just add your query statement with
cmd.CommandText = "select ....." ;

Related

How to connect the login button to my SQL Server database in C#?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using static System.Data.SqlClient.SqlConnection;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private SqlCommand cmd;
private Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("Please fill up all fields");
}
try
{
SqlCredential Librarypavilion = null;
SqlConnection SqlConnection = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=", Librarypavilion, ";Integrated Security=True");
SqlCommand; cmd = new SqlCommand("select * from login where username = #username and password = #password");
cmd.Parameters.AddWithValue("#username", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show(" User is successfully logged in");
}
else
{
MessageBox.Show("Login unsuccessful");
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
if (textBox2.Text == "")
{
MessageBox.Show("Please fill up password");
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 frm2 = new WindowsFormsApp1.Form2();
frm2.Show();
}
}
internal class sqlConnection
{
}
}
I'm quite just learning C# using vs. I am trying to connect the login button into the SQL I created. I can't run the program. it keeps giving me the error
SqlConnection does not contain a constructor that takes 3 arguments.
How do I solve it?
Your primary issue is that your connection string isn't right. It contains spurious ", which makes C# think you have three parameters. There are also other strange syntax errors.
There are other improvements:
On the first line, && should be ||. You also need to bail out if the fields are not filled.
SqlCredential is unnecessary, but you may want to put the connection string in a settings file.
SqlDataAdapter and DataTable are only necessary if you want to use data-binding to your UI. Otherwise you can use ExecuteReader and loop it whil (reader.Read())
In this case, you don't even need that, because you only check for existence of a row. So you can just use cmd.ExecuteScalar
You need to pass the connection object to the command, and you need to open the connection.
You need to dispose the connection and command with using.
Always pass the exact parameter type, using SqlDbType, along with the length, precision or scale if relevant.
Never store plain-text passwords. Salt-and-hash them, and compare the hashes on the server. Do not retrieve the stored hash to the client app.
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text =="")
{
MessageBox.Show("Please fill up all fields");
return; //make sure to bail out
}
try
{
const string query = #"
select 1
from [login]
where username = #username
and password = #password;
";
using (var conn = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=Librarypavilion;Integrated Security=True")
using (var cmd = new SqlCommand(query, conn)
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 255).Value = textBox1.Text;
cmd.Parameters.Add("#password", SqlDbType.VarBinary, 128).Value = HashPassword(textBox1.Text, textBox2.Text);
conn.Open();
var exists = (cmd.ExecuteScalar() as int) == 1;
conn.Close();
if (exists)
{
MessageBox.Show(" User is Successfully login");
}
else
{
MessageBox.Show("unsuccessful");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Consider using async and await to keep the UI alive.
private async void button1_Click(object sender, EventArgs e)
{
.....
await conn.OpenAsync();
var exists = ((await cmd.ExecuteScalarAsync()) as int) == 1;
conn.Close();

SQL not working on c# but working in SQL Server Management Studio

Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.
Why is the table not being updated?
There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database
The view is a left outer join, meaning that it shows the values that need to be update by the by.
[sql][2]
database diagram
Form
How can this be fixed, its been like this for two days.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace ComicBookShop
{
public partial class orders_confirm : Form
{
public orders_confirm()
{
InitializeComponent();
}
//database details
string connString = "Data Source = BLAH BLAH BLAH";
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
ManagmentMain fm = new ManagmentMain();
fm.Show();
}
private void orders_confirm_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView5.AutoGenerateColumns = true;
dataGridView5.DataSource = dt;
}
}
}
con.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
this is the part of the code where the data should be inserted
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Try setting parameters with their corresponding data types:
command.Parameters.Add("orderid", SqlDbType.Int);
command.Parameters["orderid"].Value = int.Parse(txtorder.Text);
Do the same for staffid.
I think the issue is you are passing string where int is expected.

c# : How to get data from database and pass to another form?

I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}

C# login form doesn`t work

I`ve made a login form with access db, which I only need the password from.
The connection to db is successful, but when I press the button, the messagebox shows me "incorrect password", even if I insert a correct one from my db.
here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace TAC_receptie
{
public partial class login : Form
{
OleDbConnection connection = new OleDbConnection();
public login()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:login1.accdb;Persist Security Info=False;";
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText="select * from user1 where Password =' " +txtPassword.Text+ " '";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count == 1)
{
date_personale Form = new date_personale();
Form.Show();
}
else
{
if (count > 1)
{
MessageBox.Show("duplicat!!!");
}
if (count < 1)
{
MessageBox.Show("parola incorecta!!!");
}
}
connection.Close();
}
private void login_Load(object sender, EventArgs e)
{
try
{
connection.Open();
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error"+ ex);
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
btnLogin.PerformClick();
}
}
}
remove unnecessary space from
Password =' " +txtPassword.Text+ " '"
to
Password ='" +txtPassword.Text.Trim()+ "'"

Button click isnt getting triggered on hitting the enter key

I am trying to emulate a button click when the enter key is pressed in a text box. I have used this before too but it just doesn't seem to work now.
Please check the code I am using below and let me know if I missed something. I have been away from coding for almost a year now maybe I am missing something?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
String uname, password, query;
int counter = 0;
public Form1()
{
InitializeComponent();
}
private void login_Click(object sender, EventArgs e)
{
verify();
}
private void pass_KeyDown(Object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
verify();
}
}
private void verify()
{
uname = name.Text; //Initialize variables
password = pass.Text;
uname = uname.Trim(); //Sanitize input
password = password.Trim();
query = "SELECT * FROM login WHERE uname = #uname AND pass = #pass";
string conString = Properties.Settings.Default.libConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand(query, conn))
{
cmd.Parameters.AddWithValue("#uname", uname);
cmd.Parameters.AddWithValue("#pass", password);
cmd.ExecuteNonQuery();
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
counter = 1;
Variables.username = reader["uname"].ToString();
Variables.passw = reader["pass"].ToString();
if (reader["regid"].ToString() != null)
{
Variables.regid = reader["regid"].ToString();
}
MessageBox.Show(Variables.username + ", you are now logged in!");
}
if (counter == 0)
{
MessageBox.Show("Invalid details");
}
}
}
}
}
}
I am coding in C# in the IDE Visual Studio 2012
Whenever you create a method with the intention to handle an event, you need to make sure you register the method as a handler to the desired event. If you are not doing so the program will not guess that your method was meant to be an event handler.
try this :
if (args.KeyCode == Keys.Return)
{
login_Click.PerformClick();
}

Categories