I have 3 forms in my c# winform app ,
Login
Data Entry
Dashboard with Graphs
Now after login a user must only access data entry form , but after admin login he must get both the form access .How to do this .
For form opening i am using this ..but how to modify it i am not getting,as every time that "login not successful" is also showing
Data_Entry f = new Data_Entry();
f.Show();
And here is 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;
namespace Mechanical_Straightening_Dies
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.ActiveControl = comboBox1;
comboBox1.Focus();
}
private void Btnexit_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit();
}
private void Btnlogin_Click(object sender, EventArgs e)
{
string user = comboBox1.Text;
string pass = textBox1.Text;
if(user == "ADMIN" && pass == "admin")
{
MessageBox.Show("Login Successfull as ADMIN");
FrmDashBoard f = new FrmDashBoard();
f.Show();
this.Hide();
}
if(user == "USER" && pass == "password")
{
MessageBox.Show("Login Successfull as USER");
FrmDataEntry f = new FrmDataEntry();
f.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
textBox1.Focus();
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Btnlogin.PerformClick();
}
}
}
}
as every time that "login not successful" is also showing
Its because the code does not end when the login is successful and continues to execute the remaining code i.e. the next if-else statement. You should add a return statement in your first if statment like this;
if (user == "ADMIN" && pass == "admin"){
MessageBox.Show("Login Successfull as ADMIN");
FrmDashBoard f = new FrmDashBoard();
f.Show();
this.Hide();
return;
}
Also much better, you can just make it as a whole if-else if statement by making this line
if(user == "USER" && pass == "password"){...} to
else if(user == "USER" && pass == "password"){...}
I am creating a login screen for the coursework of a quiz game that I have been assigned to make. I am making this quiz in C# (windows form application).
Here is the code before I go any further:
entersing 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.IO;
namespace frmSplashScreen
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
int signUpPressed = 0;
private void button1_Click(object sender, EventArgs e)
{
string[] userdetails = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "UserDetails.txt");
foreach (string user in userdetails)
{
string[] splitDetails = user.Split(':');
Login.username = splitDetails[0];
Login.password = splitDetails[1];
label1.Text = Login.username;
label2.Text = Login.password;
if ((txtUsername.Text == Login.username) && (txtPassword.Text == Login.password))
{
MessageBox.Show("Welcome " + Login.username);
this.Hide();
frmMainMenu menu = new frmMainMenu();
menu.Show();
break;
}
else
{
if ((txtUsername.Text == Login.username) && (txtPassword.Text != Login.password))
{
MessageBox.Show("Password incorrect");
txtPassword.Text = "";
}
else
{
MessageBox.Show("Username incorrect");
txtUsername.Text = "";
txtPassword.Text = "";
}
break; //Remove this break it's not needed
}
}
}
}
}
Also here is the .txt file that it is reading the login details from:
Ryan:password
Username:password
My problem is that when I click the login button(button1), it is only reading the first line of UserDetails.txt, when I type Ryan and password into the text boxes, it works fine. However, when I type Username and password into the text boxes it comes up with the error message "Username incorrect" in a Message Box.
Also, 'Login' is a class that stores the variables for username and password
Any help would be greatly appreciated.
Thanks.
Every branch in your foreach loop ends with a break;, you never get to the second entry. Move the second break to the "Password incorrect", and allow the loop to continue if the Username does not match, maybe another one does. Check after the loop if a match has been found. (This might be easier when replacing break; with return username; in a new method CheckAndGetUser().)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace StaffFiles1._0
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void fikeToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'employee_DBDataSet1.Empoyee_GI' table. You can move, or remove it, as needed.
this.empoyee_GITableAdapter.Fill(this.employee_DBDataSet1.Empoyee_GI);
}
private void toolStripButton1_Click(object sender, EventArgs e) //new record button
{
NewRecordMenuItem.Enabled = false;
AddMenuButton.Enabled = true;
DeleteMenuButton.Enabled = true;
SaveMenuButton.Enabled = true;
EmployeeGroupBox.Enabled = true;
GenInfoGroupBox.Enabled = true;
name_TextBox.Focus();
}
private void empoyee_GIListBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void empoyee_GIListBox_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (EmpListBox.SelectedIndex == -1)
{
GenInfoGroupBox.Enabled = false;
EmployeeGroupBox.Enabled = false;
AddMenuButton.Enabled = false;
DeleteMenuButton.Enabled = false;
NewRecordMenuItem.Enabled = true;
}
}
private void AddMenuButton_Click(object sender, EventArgs e)
{
if (IsValidated())
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=c:\users\the doom's day\documents\visual studio 2012\Projects\StaffFiles1.0\StaffFiles1.0\Employee_DB.sdf");
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Empoyee_GI(Name,Father Name, Birthdate, Address, City, Zone, Province, Cell Number, Email, Employement Status, Hire Date, Renewal Date, Location, Position, BPS, Department, Gender, Maritial Status, CNIC, Employement Number)VALUES('"+name_TextBox.Text+"','"+father_Name_TextBox.Text+"','"+birthdate_DateTimePicker.Text+"','"+address_TextBox.Text+"','"+city_ComboBox.Text+"','"+zone_ComboBox.Text+"','"+province_ComboBox.Text+"','"+cell_Number_TextBox.Text+"','"+email_TextBox.Text+"','"+employement_Status_ComboBox.Text+"','"+hire_Date_DateTimePicker.Text+"','"+renewal_Date_DateTimePicker.Text+"','"+location_ComboBox.Text+"','"+position_ComboBox.Text+"','"+bPS_ComboBox.Text+"','"+department_ComboBox.Text+"','"+gender_ComboBox.Text+"','"+maritial_Status_ComboBox.Text+"','"+cNICTextBox.Text+"','"+employement_Number_TextBox.Text+"') ",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Added", "Working", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private bool IsValidated()
{
Regex CN = new Regex(#"^[0-9]{5}-[0-9]{7}-[0-9]{1}$");
Regex CL = new Regex(#"^[0-9]{4}-[0-9]{7}$");
Regex EM = new Regex(#"^[a-zA-Z0-9]{1,20}#[a-zA-Z0-9]{1,20}.[a-zA-Z]{2,3}$");
if (name_TextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Name Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
name_TextBox.Focus();
return false;
}
if (father_Name_TextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Father Name Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
father_Name_TextBox.Focus();
return false;
}
if (cNICTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("CNIC Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cNICTextBox.Focus();
return false;
}
if (!CN.IsMatch(cNICTextBox.Text))
{
MessageBox.Show("CNIC Format should be like 11111-1111111-1", "Format Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cNICTextBox.Clear();
cNICTextBox.Focus();
return false;
}
if (cell_Number_TextBox.Text != string.Empty)
{
if (!CL.IsMatch(cell_Number_TextBox.Text))
{
MessageBox.Show("Cell Number Format should be like 0300-1234567", "Format Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cell_Number_TextBox.Clear();
cell_Number_TextBox.Focus();
return false;
}
}
if (email_TextBox.Text != string.Empty)
{
if (!EM.IsMatch(email_TextBox.Text))
{
MessageBox.Show("Email Format should be like someone#someone.com", "Format Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
email_TextBox.Clear();
email_TextBox.Focus();
return false;
}
}
if (address_TextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Address Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
address_TextBox.Focus();
return false;
}
if (city_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("City field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (province_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Province field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (employement_Status_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Status Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (location_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Location Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (position_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Position Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (bPS_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("BPS Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (department_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Department Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (gender_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Gender Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
if (maritial_Status_ComboBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Maritial Status Field Required", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
return true;
}
private void DeleteMenuButton_Click(object sender, EventArgs e)
{
}
private void SaveMenuButton_Click(object sender, EventArgs e)
{
}
private void city_ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
}
}
When i run the code i come across this error how can i solve this can any one help please
An unhandled exception of type
'System.Data.SqlServerCe.SqlCeException' occurred in
System.Data.SqlServerCe.dll c#
This error come when i press the add record button to add the record
of the fields in the compact local database.
You have to wrap the names in square brackets if they contain spaces.
string sql ="
INSERT INTO Empoyee_GI(Name,[Father Name], Birthdate, Address, City, Zone, Province,
[Cell Number], Email, [Employement Status], Hire Date,
[Renewal Date], Location, Position, BPS, Department, Gender,
[Maritial Status], CNIC, [Employement Number])
VALUES(...);";
SqlCeCommand cmd = new SqlCeCommand(sql,con);
Note that you should also use parameterized queries to avoid sql injection!
hi evryone can you help me please.. i have a code on my windows form application using visual studio community 2015 I have a textBox the name is username the other one is password and the last is login if the user want to login and it will get a tree times error here the problem I want it automatically show the forgot password and how to recover password if the user is tree times error when he or she login the form. before I'll go to my database form i have no idea can you help please and explain how.
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;
namespace SQLSERVER_VISUALSTUDIO_COMMUNITY
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txt_Password.PasswordChar = '*';
}
private void txt_login_Click(object sender, EventArgs e)
{
if (txt_USername.Text == "" && txt_Password.Text == "")
{
MessageBox.Show("Please enter your password and user_name");
txt_USername.Clear();
txt_Password.Clear();
}
else if (txt_USername.Text == "jondygonzales" && txt_Password.Text == "sharkwebcaster")
{
MessageBox.Show("successfully log_in");
Form1 f = new Form1();
f.Show();
Form2 main = new Form2();
main.Show();
this.Hide();
}
}
}
}
What you need to do is keep a counter which you will increase by one when username and password are not valid.
You check this variable value and when it reaches 3, you show user the password recovery form.
public partial class Form1 : Form
{
int loginAttemps = 0;
public Form1()
{
InitializeComponent();
txt_Password.PasswordChar = '*';
}
private void txt_login_Click(object sender, EventArgs e)
{
if (txt_USername.Text == "" && txt_Password.Text == "")
{
MessageBox.Show("Please enter your password and user_name");
txt_USername.Clear();
txt_Password.Clear();
}
else if (txt_USername.Text == "jondygonzales" && txt_Password.Text == "sharkwebcaster")
{
loginAttempts = 0;
MessageBox.Show("successfully log_in");
Form1 f = new Form1();
f.Show();
Form2 main = new Form2();
main.Show();
this.Hide();
}
else
{
loginAttempts += 1;
if(loginAttemps == 3)
{
RecoveryForm recForm = new RecoveryForm(); // You need to use correct Form here.
recForm.Show();
this.Hide();
}
}
}
}
My question comes from a problem which I have right now. I have MainWindow, AuthenticateWindow, and AddEntryWindow which all are WinForms. In main window I have possibility to Authenticate and Add Entry into my main windows textbox. They can not add an entry until they authenticate (no problem with this). I need to add an entry to the text box which will update my main windows textbox. The problem if, how can I check if entry was added to my textbox?
I am trying to have a Save option from menu strip. I am getting an error whenever I am trying to save an empty file. How could I authenticate the saving process by Save button by having it first disabled, and enabled after entry was added?
I could always verify if if textbox had an entry but I want to have button disabled first, and enabled after entry was added. I do not have a privilege to do so as of right now.
Please ask questions if I am not clear enough.
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
if (txtDisplay.Text != string.Empty)
{
sfdSaveToLocation.ShowDialog();
}
}
MainWindow.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
// Prohibit editing.
txtDisplay.Enabled = false;
}
public string ChangeTextBox
{
get
{
return this.txtDisplay.Text;
}
set
{
this.txtDisplay.Text = value;
}
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
private void tsmiClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
sfdSaveToLocation.ShowDialog();
}
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string theFileName = sfdSaveToLocation.FileName;
EncryptDecrypt en = new EncryptDecrypt();
string encrypted = en.Encrypt(txtDisplay.Text,
storedAuth.UserName, storedAuth.Password);
MessageBox.Show(encrypted);
File.WriteAllText(theFileName, encrypted);
}
}
}
AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
string user, pass;
// Initializind ArrayList to store all data needed to be added or retrived.
private ArrayList addedEntry = new ArrayList();
// Initializing MainWindow form.
MainWindow mainWindow;
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
public AddEntryWindow(MainWindow viaParameter, string user, string pass)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
}
private void AddEntryWindow_Load(object sender, EventArgs e)
{ }
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex == -1)
{
MessageBox.Show("Please select entry type!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Each field must be filled for specified type.
// Here we are checking if all fields were filled.
else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
{
MessageBox.Show("Please fill all the fields!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int totalEntries = 0;
if(cmbType.SelectedIndex == 0)
addedEntry.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
else if(cmbType.SelectedIndex == 1)
addedEntry.Add(new AddWebSite(cmbType.Text,
txtUserName.Text, txtPassword.Text, txtURL.Text));
else if(cmbType.SelectedIndex == 2)
addedEntry.Add(new AddSerialCode(cmbType.Text,
txtSoftwareName.Text, txtSerialCode.Text));
StringBuilder stringBuilder = new StringBuilder();
foreach (var list in addedEntry)
{
if (list is AddPC)
{
totalEntries++;
AddPC tmp = (AddPC)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
totalEntries++;
AddWebSite tmp = (AddWebSite)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
totalEntries++;
AddSerialCode tmp = (AddSerialCode)list;
stringBuilder.Append(tmp.ToString());
}
}
mainWindow.ChangeTextBox = stringBuilder.ToString();
mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";
// Clearing all fields.
ClearFields();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing the Add Entry Window form.
this.Close();
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
// Deciding which data must be entered depending on
// what type is selected from combo box.
// PC
if (cmbType.SelectedIndex == 0)
{}
// Web Site
else if (cmbType.SelectedIndex == 1)
{}
// Serial Code
else if (cmbType.SelectedIndex == 2)
{}
}
private void ClearFields()
{
// Clearing all fields to the default state.
}
}
}
Regards.
It sounds like you probably just want to subscribe to the TextChanged event, which will be fired whenever the text in the textbox changes.
I can't say I really followed everything that you're doing, but I think you should be fine to just enable or disable your Save button within that event handler.
EDIT: It's not really clear where all your different components live, but you want something like:
// Put this after the InitializeComponent() call in the constructor.
txtDisplay.TextChanged += HandleTextBoxTextChanged;
...
private void HandleTextBoxTextChanged(object sender, EventArgs e)
{
bool gotText = txtDisplay.Text.Length > 0;
menuSaveButton.Enabled = gotText;
}
I'd also strongly advise you not to use ArrayList but to use the generic List<T> type. The non-generic collections should almost never be used in new code.