C# Unreachable Code Detected - c#

I've been messing around for over an hour now. I still don't know how to solve it even reading the Stackoverflow solution. The program works with the first username and password (test & password), when I typed in the second username and password (aaa & 123) it doesn't work.
public partial class Form2 : Form
{
String[] username = { "test", "aaa" };
String[] password = { "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < username.Length; i++) // <------- Unreachable Code
{
if ((txtUsername.Text.Trim() == username[i]) && (txtPassword.Text.Trim() == password[i]))
{
MessageBox.Show("Login Successful. Welcome!", "Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
break;
}
else
{
MessageBox.Show("You have entered an invalid input. Do you want to try again?", "Invalid Input", MessageBoxButtons.YesNo, MessageBoxIcon.Hand); break;
}
}
}
catch(Exception x)
{
MessageBox.Show("System Error! Please try again!", "System Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}

You have break word in both if-else branches. Remove break from else. But you will get message boxes on every loop. So you need to modify your code: move message box outside the loop.

You have logical flow control issues inside of your code. As a result, you need to move the MessageBox firing outside of your loop.
If you modify your code to use lists instead of arrays and include a bit of LINQ, you can move away from a loop altogether, as well as you can benefit from less nesting.
public partial class Form2 : Form
{
List<string> username = new List<string>{ "test", "aaa" };
List<string> password = new List<string>{ "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text.Length > 0 && txtPassword.Text.Length > 0
&& username.Any(x => x == txtUsername.Text.Trim())
&& password.Any(x => x == txtPassword.Text.Trim()))
{
MessageBox.Show(
"Login Successful. Welcome!",
"Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
}
else
{
MessageBox.Show(
"You have entered an invalid input. Do you want to try again?",
"Invalid Input",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
}
}
catch(Exception x)
{
MessageBox.Show(
"System Error! Please try again!", "System Error",
MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}

Related

Comparing Textbox values to a database

So, I'm working on a project for a class of mine. The first part is a login form, which requires a user to enter a username and a password. When the login button is hit, the program is to compare the textbox text to what is in a datatable. Only problem is, I'm having a tough time doing this. I tried doing it with LINQ statements, but that made the values different from what I was expecting when I went to debug it. Am I doing something wrong here?
Heres the code for the form.
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.Entity;
using System.Data.Entity.Validation;
namespace mcshonsey_Final
{
public partial class LoginForm : Form
{
SortingClass sort = new SortingClass();
mcshonsey_FinalProject.UserShowDBEntities dbcontext = null;
public LoginForm()
{
InitializeComponent();
textBox1.Text = "";
textBox2.Text = "";
textBox1.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
if (dbcontext != null)
dbcontext.Dispose();
dbcontext = new mcshonsey_FinalProject.UserShowDBEntities();
dbcontext.UserTables
.OrderBy(entry => entry.UserID)
.Load();
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("You must enter a password or username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Focus();
}
/*else
{
ShowSelectForm ssf = new ShowSelectForm(this, sort);
Hide();
ssf.Show();
}*/
string num1 = Convert.ToString(textBox1.Text);
string num2 = Convert.ToString(textBox2.Text);
var user =
from use in dbcontext.UserTables
where use.UserName == num1
select use;
var user2 =
from pas in dbcontext.UserTables
where pas.UserPassword == num2
select pas;
if (textBox1.Text.Equals(user) && textBox2.Text.Equals(user2))
{
ShowSelectForm ssf = new ShowSelectForm(this, sort);
Hide();
ssf.Show();
}
else
{
MessageBox.Show("Incorrect username and/or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Focus();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to quit?", "Exit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Application.Exit();
}
}
private void LoginForm_Load(object sender, EventArgs e)
{
}
}
}
The SortingClass is a class to sort through the datatable, but that's for a later time.
The UserShowDBEntities is the database itself.
I'm not a user of LINQ to SQL but I believe the following would work for you.
Basically, I made the following changes:
1. Combined the username and password check into a single WHERE clause
2. If you get a matching record back (i.e. Enumerable.Count check) it means the username and password matched a record and thus were correct.
private void button1_Click(object sender, EventArgs e)
{
if (dbcontext != null)
dbcontext.Dispose();
dbcontext = new mcshonsey_FinalProject.UserShowDBEntities();
dbcontext.UserTables
.OrderBy(entry => entry.UserID)
.Load();
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("You must enter a password or username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Focus();
}
/*else
{
ShowSelectForm ssf = new ShowSelectForm(this, sort);
Hide();
ssf.Show();
}*/
var user =
from use in dbcontext.UserTables
where use.UserName == textBox1.Text && use.Password == textBox2.Text
select use;
if (Enumerable.Count(user) > 0)
{
ShowSelectForm ssf = new ShowSelectForm(this, sort);
Hide();
ssf.Show();
}
else
{
MessageBox.Show("Incorrect username and/or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox1.Focus();
}
}
I hope your data source is filled and your password is not encrypted in the database.
var user = dbcontext.UserTables.FirstOrDefault( u => u.UserName == textBox1.Text && u.UserPassword == textBox2.Text);
if(user != null)
// Check
else
// Failed
If textBox1 is the username and textBox2 is the password, this should work.

I need to search an Object Array I created for a specific user-generated input and return one of the contents of the same element containing the input

I made a class I named DictionarySample to represent the fact that the procedures within this class are supposed to replicate several similar Dicitionary functionalities
public class DictionarySample
{
public int idNumb {get; set;}
public string fn { get; set; }
public string ln { get; set; }
public string adr { get; set; }
public string bday { get; set; }
public int num { get; set; }
}
via an array which I have initiated in the form class.
namespace Project
{
public partial class Form1 : Form
{
public int lastElementIndex = 0;
DictionarySample[] database = new DictionarySample[1000];
PriorityQueueSample[] line = new PriorityQueueSample[1000];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void buttonApply_Click(object sender, EventArgs e)
{
bool digitCharactersInfirst = textBoxFirstName.Text.Any(char.IsDigit);
bool digitCharactersInlast = textBoxLastName.Text.Any(char.IsDigit);
if (String.IsNullOrEmpty(textBoxIDNumber.Text))
{
MessageBox.Show("Enter an ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (int.Parse(textBoxIDNumber.Text) < 100000 || int.Parse(textBoxIDNumber.Text) > 999999)
{
MessageBox.Show("Invalid ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (String.IsNullOrEmpty(textBoxFirstName.Text))
{
MessageBox.Show("Enter First Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (digitCharactersInfirst == true)
{
MessageBox.Show("First Name can't contain digits. Please re-enter Given Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
textBoxFirstName.Text = String.Empty;
}
else if (String.IsNullOrEmpty(textBoxLastName.Text))
{
MessageBox.Show("Enter Last Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (digitCharactersInlast == true)
{
MessageBox.Show("Last Name can't contain digits. Please re-enter Surname.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
textBoxLastName.Text = String.Empty;
}
else if (String.IsNullOrEmpty(textBoxAdr.Text))
{
MessageBox.Show("Enter Address.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (String.IsNullOrEmpty(textBoxBirthday.Text))
{
MessageBox.Show("Enter Date of Birth.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
string c = "Proceed with the following Account Information? \n" + textBoxFirstName.Text + " " + textBoxLastName.Text + "," + textBoxIDNumber.Text + "\nAddress: " + textBoxAdr.Text + "\nBirthday: " + textBoxBirthday.Text;
DialogResult dialogResult = MessageBox.Show(c, "Verify information", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
int a = int.Parse(textBoxIDNumber.Text);
lastElementIndex++;
DictionarySample d = new DictionarySample();
d.idNumb = a;
d.fn = textBoxFirstName.Text;
d.ln = textBoxLastName.Text;
d.adr = textBoxAdr.Text;
d.bday = textBoxBirthday.Text;
d.num = lastElementIndex;
database[lastElementIndex] = d;
textBoxIDNumber.Text = String.Empty;
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
textBoxAdr.Text = String.Empty;
textBoxBirthday.Text = String.Empty;
string prio = "You may now Line-Up.\nYour priority number is:\t" + lastElementIndex;
MessageBox.Show(prio, "Take Note", MessageBoxButtons.OK);
}
else if (dialogResult == DialogResult.No)
{
}
}
The program goes like this: It asks the user for an IDNumber, Name, Address, and Birthday, then internally generates a priority number based on their order of application, which upon the click of the "Apply" button stores the User Info in my array named database.
*Check out a screen capture of form at http://tinypic.com/r/vfgkyh/8
After the user has applied, he then has to input his ID Number in the second panel which upon the click of the Line-Up button must look for the ID Number in the database and return the corresponding priority number, which will then both be inserted into another array with the functionalities of a Priority Queue.
My current code for the click of this Line-Up button goes as follows
private void buttonLineUp_Click(object sender, EventArgs e)
{
int temp = int.Parse(textBoxIDLINE.Text);
if (String.IsNullOrEmpty(textBoxIDLINE.Text))
{
MessageBox.Show("Enter an ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (int.Parse(textBoxIDLINE.Text) < 100000 || int.Parse(textBoxIDLINE.Text) > 999999)
{
MessageBox.Show("Invalid ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
for (int looper = 0; looper < 500; looper++)
{
//if (d.idNumb.database[looper] == int.Parse(textBoxIDNumber.Text))
//{
//}
//int idnb = 0;
//int priorityk = 0;
foreach (DictionarySample d in database)
{
if (d.idNumb == int.Parse(textBoxIDNumber.Text))
{
PriorityQueueSample lin = new PriorityQueueSample();
lin.idNumber = d.idNumb;
lin.pnumb = d.num;
labeldisplay.Text = d.idNumb + "," + d.num;
}
}
}
}
I haven't started inputting the data into the priorityqueue array because I can't access the data from the Database array. Please help.
If idNumb is unique then instead of:
DictionarySample[] database = new DictionarySample[1000];
you could use:
Dictionary<int, DictionarySample> = new Dictionary<int, DictionarySample>();
And then save the idNumb as the key of the dictionary.

how to loop through an entire datagrid in f1 and pass values as string to label in f2

i have a datagrid in say form1 with some records in it and form 2 as a registration form which shows as dialog to form1. now upon a new registration with form2 i need to check whether the client has already been registered or not with records in the datagrid and display a message saying client already exist. so far i've been successful in passing a selected row in form1 as string to compare what ever client name being entered in form2. now i would like to know how to loop through entire datagrid and pass them as values to a label in form2 to enhance my checking up. below is how i do passing from form1 to form2
form 1 string declaration
public string strlabel2
{
get { return txtboxClearingAgent.Text; }
}
this where txtboxClearingAgent is taken from
private void kryptonDataGridView1_Validated(object sender, EventArgs e)
{
txtboxClearingAgent.Text = kryptonDataGridView1.SelectedRows[0].Cells["Clearing Agent Name"].Value.ToString();
and passed to form2 through showdialog
private void kryptonButton1_Click_1(object sender, EventArgs e)
{
frmNewClient frmNewClient1 = new frmNewClient();
frmNewClient1._strData = strlabel2;
frmNewClient1.ShowDialog();
and received in form 2
public string _strData
{
set { lblDatagrid.Text = value; }
}
and if statement to check during insertion
if (lblDatagrid.Text == txtboxClientName.Text)
{
MessageBox.Show("Client exist", "Checking Client(s) List", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else if (lblDatagrid.Text != txtboxClientName.Text)
{
DialogResult result = MessageBox.Show("Do you want to save this Entry?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
MessageBox.Show("New Client Entry has successfully been Saved", "Saving Client(s) Entry", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (result == DialogResult.No)
{
return;
}
int result1 = cmd.ExecuteNonQuery();
lblDat.Text = "1";
}

C# Displaying error messages by completing a simple registration form

I'm new about C#, I learnt C programmation for one year now.
I created a Window Form which asks the user to complete a registration form.
My registration form
I'd like to display an error message below the buttons when a field is not filled or a field isn't well used.
I used this basic code :
private void button1_Click(object sender, EventArgs e)
{
if (!isOkay(userTextBox.Text))
{
label5.Text = "Please, enter an username.";
label5.Visible = true;
}
else if (!isOkay(mailTextBox.Text))
{
label5.Text = "Please, enter a mail address.";
label5.Visible = true;
}
else if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
{
label5.Text = "Please, match both mails addresses.";
label5.Visible = true;
}
else if (!isOkay(passwordTextBox.Text))
{
label5.Text = "Please, enter a password.";
label5.Visible = true;
}
else
{
label5.Text = "Valid form, yay !";
label5.Visible = true;
}
}
private Boolean isOkay(string textBoxContent)
{
return (textBoxContent.Length > 0 || textBoxContent.Equals(null));
}
Are there any elegant or optimized ways to do it properly ? I found some Error providers, but apparently error providers open a pop-up, and I just want a "red error message below buttons".
Can you give me some help ? :)
Given a class like this
public class RequiredFieldsError
{
private List<string> errors;
public RequiredFieldsError()
{
errors = new List<string>();
}
public int Count
{
get{return errors.Count;}
}
public void AddField(string errorField)
{
errors.Add(errorField);
}
public override string ToString()
{
if(errors.Count == 0)
return string.Empty;
else
{
string fields = string.Join(Environment.NewLine, errors);
fields = "The following fields contains errors:" + Environment.NewLine + fields;
return fields;
}
}
}
then you could change your code to
private void button1_Click(object sender, EventArgs e)
{
RequiredFieldsError rfe = new RequiredFieldsError();
if (!isOkay(userTextBox.Text))
rfe.AddField("User name missing, Please, enter an username.";
if (!isOkay(mailTextBox.Text))
rfe.AddField("Email address missing, Please, enter a mail address.";
if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
rfe.AddField("Email address doesn't match the confirmation email");
if (!isOkay(passwordTextBox.Text))
rfe.AddField("Password missing, Please, enter a password.";
if(rfe.Count > 0)
{
// MessageBox.Show(rfe.ToString());
label5.Text = rfe.ToString()
label5.Visible = true;
}
}
This approach avoids the unnerving situation (for your user) when he/she receives an error message, he/she fixes it just to receive another error message at the next attempt to confirm the form.
Of course your label should be tall enough to show all the possible messages or just use a messagebox.
I suggest also to change your IsOkay function to
private Boolean isOkay(string textBoxContent)
{
return !string.IsNullOrWitheSpace(textBoxContent));
}
this will handle also a string composed just of one or more spaces. (not null and not length==0)
You can use ErrorProvider. It show's an error icon after your textbox.
For one of your textboxes for example:
if (!isOkay(userTextBox.Text))
{
errorProvider1.SetError(userTextBox "yourmessage");
}
else{
errorProvider1.Clear();
}
Link: http://www.dotnetperls.com/errorprovider

Issue validating user credentials in custom authentication form [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have problem with my login system here.
I can go to next form when I input the valid username and password.
And when I input wrong username and correct password, still I can go to next form.
And correct username and wrong password I can still go to next form.
What is the correct code for not letting go to next from if my username or password is wrong?
Here's my code.
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text == "username")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
}
if (tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
}
}
I can only hazard a guess at what you are asking, but if you want the username and password to both be correct before showing the form use this instead
if (tbUsername.Text == "username")
{
if(tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
MessageBox.Show("Wrong password", "Error");
}
}
else
{
if(tbPassword.Text == "password")
{
MessageBox.Show("Wrong username", "Error");
}
else
{
MessageBox.Show("Wrong username and password", "Error");
}
}
You can nest the password check if block inside the successful username if block:
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text == "username")
{
if (tbPassword.Text == "password")
{
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
}
}
else
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
}
}
The way you have it the else block for the username check is executing when the username is wrong then the code continues to the password check. You need to make sure the form is shown only after checking both username and password.
Alternatively, you can check both individually and return from the click event if the username or password is incorrect like so:
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbUsername.Text != "username")
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Username! ", "Error");
return;
}
if (tbPassword.Text != "password")
{
SystemSounds.Hand.Play();
MessageBox.Show("Invalid Password! ", "Error");
return;
}
//If we got here in code execution, then both username and password are correct
AdminMainMenu x = new AdminMainMenu();
x.Show();
t.Play();
this.Dispose();
}

Categories