How to fix Error in argument exception system - 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;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pwnew.PasswordChar = '*';
pwtxt.PasswordChar = '*';
signup.Visible = false;
}
private void signupbtn_Click(object sender, EventArgs e)
{
signup.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (unnew.Text != null && pwnew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
MessageBox.Show("Error");
}
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (untxt.Text != null && pwtxt.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM userTable where username = '" + untxt.Text + "' and password '" + pwtxt.Text + "'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form2 meLoad = new Form2();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
obj.conn.Close();
MessageBox.Show("Successfully Login");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No empty fields are allowed");
}
{
}
}
}
}
Hi, I am completely new to c#, im having this error whenever i click sign up. It tells me to check the line 44 which is
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
Im a student, adn dont have enough background in programming, i'd appreciate someone's help. I really want to learn this programming language, and im currentlty having troubles.enter image description here Thank u so much.
I use this for Connection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\hp\source\repos\WindowsFormsApp1\WindowsFormsApp1\UserDB.mdf;'Integrated Security=True";
}
}

It seems something is breaking to connect your database.
Please double check your connection string,If you need help for connection string, you may visit https://www.connectionstrings.com/
This tutorial may be helpful for you to connect database using c#.
https://www.guru99.com/c-sharp-access-database.html

Related

This code shows me that "CommandText has not been initialized"

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 ....." ;

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()+ "'"

Why do i keep getting a blank form C#

I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form 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.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form 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.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.
You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation

How to display data from database to another form by calling it from another form

I have created a form in C# for the user to login and when they successfully login, the data of the user who had logged in will be displayed to another form in a gridview. The problem here is when the user successfully logged in then goes to the other form the data was not displayed and i get an error "object reference not set to an instance of an object".
here is my code:
LoginFaculty.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ClassScheduling
{
public partial class LogInFaculty : Form
{
public LogInFaculty()
{
InitializeComponent();
}
private void btnSignInFaculty_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from database.faculty where FullName='" + this.txtBoxUserNameFaculty.Text + "' and Password= '" + this.txtBoxPasswordFaculty.Text + "'", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
string lastname = myReader.ToString();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("LogIn Sucessfully");
this.Hide();
FacultyLoadForm newForm = new FacultyLoadForm();
newForm.Show();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and password ....Access Denied!");
}
else
MessageBox.Show("Username or Password is incorrect");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnExitFaculty_Click(object sender, EventArgs e)
{
Account newForm = new Account();
newForm.Show();
this.Hide();
}
}
}
then for my FacultyLoad.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ClassScheduling
{
public partial class LogInFaculty : Form
{
public LogInFaculty()
{
InitializeComponent();
}
private void btnSignInFaculty_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from database.faculty where FullName='" + this.txtBoxUserNameFaculty.Text + "' and Password= '" + this.txtBoxPasswordFaculty.Text + "'", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
string lastname = myReader.ToString();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("LogIn Sucessfully");
this.Hide();
FacultyLoadForm newForm = new FacultyLoadForm();
newForm.Show();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and password ....Access Denied!");
}
else
MessageBox.Show("Username or Password is incorrect");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnExitFaculty_Click(object sender, EventArgs e)
{
Account newForm = new Account();
newForm.Show();
this.Hide();
}
}
}
That's it! I really have no idea why I keep getting that error and I've tried every possible solution I know. If anyone know, please do tell me.
create a constructor for FacultyLoadForm and pass all the required values from login form after successful login.
Do something like this..
Code for LoginFaculty.cs:
private void btnSignInFaculty_Click(object sender, EventArgs e)
{
try
{
...
....
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("LogIn Sucessfully");
this.Hide();
//Use Overloaded Constructor..
FacultyLoadForm newForm = new FacultyLoadForm(this.txtBoxUserNameFaculty.Text , this.txtBoxPasswordFaculty.Text);
newForm.Show();
}
...
...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code for FacultyLoad.cs
// Global Variables, which will be used for Page Load Event to get data...
string LoginUserName,LoginUserPassword;
// Over Loaded Constructor..
public LogInFaculty(string UserName,string Password)
{
LoginUserName=UserName;
LoginUserPassword=Password;
InitializeComponent();
}
and now in FacultyLoad.cs Pages Load Event write your code for filling Grid View.
U got the error because u did not pass the user ID to the detail form Properly. there are many ways to do it. but more acceptable way is save the user ID into a static field of a static class after successful Login. so that you can use that user ID from from any form with out sending the User ID again and again. Please follow the following steps.
Create a Static Class name Global.cs at your project. and add a static member named UserID
public static class Global
{
public static string UserID;
}
then at your log in form do the following in your log in button click event
// if log in successful then
Global.UserID= txtUserID.Text;
// call the details form
// hide the login form
In detail form you can retrieve the UserID in the Following Way
string userID=Global.UesrID;
// now you can user this ID to retrive the detail value of that User

Categories