Accessing object from another method in visual studio 2015 form buttons - c#

I'm working on an interface for a user to enter a name, number, and initial balance to create an account. Then allowing the user to withdraw or deposit money through a class called Customer with Deposit and Withdrawal methods.
I've done the account creation part successfully. The problem is that I've created a new object called cust1 when the account successfully completes, but that object cannot be accessed when the user presses the button to apply the deposit or withdrawal.
the interface
The full code as of right now: http://pastebin.com/6HHdMLV1
The object declaration is at the bottom of this code here, this is the method for when the user presses the account create button.
private void CreateAccountButton_Click(object sender, EventArgs e)
{
string fullName = " ";
int accountNumber = 0;
double initialBalance = 0.00;
Boolean validName = false;
Boolean validAccount = false;
Boolean validBalance = false;
if (string.IsNullOrWhiteSpace(AccountNameInput.Text))
{
MessageBox.Show("Please enter your full name.", "Error",
MessageBoxButtons.OKCancel);
}
else if(Regex.IsMatch(AccountNameInput.Text, #"^[a-zA-Z ]+$"))
{
if(AccountNameInput.Text.Contains(" "))
{
fullName = AccountNameInput.Text;
validName = true;
}
else
{
MessageBox.Show("Full name must contain a space.", "Error",
MessageBoxButtons.OKCancel);
}
}
else
{
MessageBox.Show("Name must not contain numbers or special characters.", "Error",
MessageBoxButtons.OKCancel);
}
if (string.IsNullOrWhiteSpace(AccountNumberInput.Text))
{
MessageBox.Show("Please enter your account number", "Error",
MessageBoxButtons.OKCancel);
}
else if(Regex.IsMatch(AccountNumberInput.Text, #"^[0-9]+$"))
{
accountNumber = Convert.ToInt32(AccountNumberInput.Text);
validAccount = true;
}
else
{
MessageBox.Show("Must contain only numbers.", "Error",
MessageBoxButtons.OKCancel);
}
if (string.IsNullOrWhiteSpace(InitialBalanceInput.Text))
{
MessageBox.Show("Please enter your initial balance", "Error",
MessageBoxButtons.OKCancel);
}
else if (Regex.IsMatch(AccountNumberInput.Text, #"^[0-9.]+$"))
{
initialBalance = Math.Round(Convert.ToDouble(InitialBalanceInput.Text),2);
validBalance = true;
}
else
{
MessageBox.Show("Initial balance must contain only numbers and a decimal point.", "Error",
MessageBoxButtons.OKCancel);
}
if(validName == true && validAccount == true && validBalance == true)
{
AccountBalanceDisplay.Text = "$" + Convert.ToString(initialBalance);
Customer cust1 = new Customer(fullName, accountNumber, initialBalance);
}
}
And here is the method that isn't able to access the cust1 object.
private void ApplyButton_Click(object sender, EventArgs e)
{
double userInput = Convert.ToDouble(AmountInput.Text);
if (DepositRButton.Checked)
{
cust1.Deposit(userInput);
}
}

You simply need to add a reference to the object outside of the method that you create it in.
private cust1;
private void CreateAccountButton_Click(object sender, EventArgs e)
{
//Your code
}
And now you can just replace
Customer cust1 = new Customer(fullName, accountNumber, initialBalance);
with
cust1 = new Customer(fullName, accountNumber, initialBalance);
Assuming that you need more than one customer you might want to use a list. This way you can just create the object like you did and add it to that list.
List<Customer> CustomerList = new List<Customer>();
private void CreateAccountButton_Click(object sender, EventArgs e)
{
//Rest of your code
if(validName == true && validAccount == true && validBalance == true)
{
AccountBalanceDisplay.Text = "$" + Convert.ToString(initialBalance);
Customer cust1 = new Customer(fullName, accountNumber, initialBalance);
CustomerList.Add(cust1)
}
And you can access the customer by it's position on the list:
private void ApplyButton_Click(object sender, EventArgs e)
{
double userInput = Convert.ToDouble(AmountInput.Text);
if (DepositRButton.Checked)
{
CustomerList[0].Deposit(userInput);
}
}

Related

how do i allow my listview to be stored so that i can pull to display from another class or form

{
public partial class BookNow : Form
{
private const int CP_NOCLOSE_BUTTON = 0x200;
private string title;
private string ad; //Adult
private string ch; //Child
private string sd; //StartDate
private string rd; //ReturnDate
private string ins; //Insurance
private string extb; //Extra Baggage
private int people;
private double total = 0;
Cart c = new Cart();
ArrayList arr = new ArrayList(30);
public BookNow()
{
InitializeComponent();
adult.SelectedIndex = 1;
child.SelectedIndex = 0;
insuranceNo.Checked = true;
tenKG.Checked = true;
}
private void Next_Click(object sender, EventArgs e)
{
if (tour.Text == "Choose A Tour")
{
MessageBox.Show("Please select a tour of your choice", "Choice of Tour Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
tour.Focus();
}
else if (adult.Text == "0" && child.Text == "0")
{
MessageBox.Show("Please select number of Travellers", "Number of Travellers Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
adult.Focus();
}
else if (startDate.Text == returnDate.Text)
{
MessageBox.Show("Start Date and Return Date Cannot be the Same. Please Edit Dates to Continue", "Dates Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
returnDate.Focus();
}
else
{
if (tour.Text == "TSIN - Singapore's Discovery")
total += 1299.00;
else if (tour.Text == "TSEO - Seoul's Highlights")
total += 1899.00;
else if(tour.Text == "TTAI - Taiwan Spotlight")
total += 1000.00;
title = tour.Text;
ad = adult.Text;
ch = child.Text ;
sd = startDate.Text;
rd = returnDate.Text;
if (insuranceYes.Checked)
{
ins += insuranceYes.Text;
total += 29.99;
}
else
{
ins = insuranceNo.Text;
}
if (tenKG.Checked)
extb = tenKG.Text;
else if (twentyKG.Checked)
{
extb = twentyKG.Text;
total += 50.00;
}
else
{
extb = thirtyKG.Text;
total += 80.00;
}
people = int.Parse(ad) + int.Parse(ch);
total = total * people;
cartNow(c);
total = 0;
var result = MessageBox.Show("Added To Cart, Continue To Your Cart?","Cart Updated", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
c.add(c);
Hotel h = new Hotel();
h.Show();
}
}
}
private void Reset_Click(object sender, EventArgs e)
{
}
private void Cart_Click(object sender, EventArgs e)
{
c.Show();
}
This method is to Add into my listview so that i can display and i tried using an array but still unable to do it
public void cartNow (Cart instance)
{
ListViewItem lvl = new ListViewItem(arr[0].ToString());
lvl.SubItems.Add(arr[1].ToString());
lvl.SubItems.Add(ch);
lvl.SubItems.Add(sd);
lvl.SubItems.Add(rd);
lvl.SubItems.Add(ins);
lvl.SubItems.Add(extb);
lvl.SubItems.Add(total.ToString("c2"));
instance.listView1.Items.Add(lvl);
}
private void Close_Click(object sender, EventArgs e)
{
var confirmResult = MessageBox.Show("Closing the booking System will result in clearing the Cart.","Are You sure you want to continue?",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
}
public void showCart()
{
c.Show();
}
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
return myCp;
}
}
}
}
I am able to open up my Cart and display the items inside my listview but when i close the cart and want to run from another form it does not work as the information becomes empty e.g(variable ad which has the number of adults becomes null and nth will be displayed if i try to run the cartNow() method from another class

how to store <List> into a database in winform C#?

I have little experience setting up databases with C#. So, I want to store predefined contents of a list, also add values and remove values in session as the form runs.As from the list, URLs are blocked in the WebBrowser control, according to the contents. I will add snippets below.
private List<string> BlockList = new List<string>() { "http://www.google.com", "http://www.google.co.uk", "http://www.bing.com" };
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
string[] BlockArray = BlockList.ToArray();
for (int i = 0; i < BlockArray.Length; i++)
{
if (e.Url.Equals(BlockList[i]))
{
e.Cancel = true;
MessageBox.Show("Booyaa Says No!", "NO NO NO", MessageBoxButtons.OK, MessageBoxIcon.Hand); // Block List Error Message
}
}
}
private void button6_Click_1(object sender, EventArgs e)
{
string url = textBox2.Text;
// Get if the user entered the right password
GetPass pass = new GetPass(password);
// Check this with a dialog result
DialogResult result = pass.ShowDialog();
if (result == DialogResult.OK)
{
BlockList.Add(url);
MessageBox.Show("Added " + url + " to blocklist.");
textBox2.Clear();
}
else
{
MessageBox.Show("Booyaa Says Wrong Password", "Wrong Password", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
private void button7_Click_1(object sender, EventArgs e)
{
string url = textBox2.Text;
// Get if the user entered the right password
GetPass pass = new GetPass(password);
// Check this with a dialog result
DialogResult result = pass.ShowDialog();
if (result == DialogResult.OK)
{
BlockList.Remove(url);
MessageBox.Show("Removed " + url + " from blocklist.");
textBox2.Clear();
}
else
{
MessageBox.Show("Booyaa Says Wrong Password", "Wrong Password", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}

Multiple conditions in Windows Phone Silverlight development

I am beginning Windows Phone development with Silverlight and web services. I have a web services for User Login where I have two checks before the user is Allowed to log in. I am unable to perform both checks. Only one check is called. My code:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
if (!e.Result)
{
MessageBox.Show("User is Not a Student. Unable to Login", "Error", MessageBoxButton.OK);
return;
}
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
if (e.Result)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
}
If the Credentials are valid the user is able to log in whether he/she is a student user or not. How can I make both check to be executed?
The way this is coded, I don't believe that you can guarantee the order in which the service calls will return. Therefore, you could store the results from each call, then call a 3rd method that evaluates that both calls have returned. Another option would be to chain the calls so that it does not check if the user is a student until it returns from the credential check and passes, then you can navigate from the return of that call.
First option example:
private void login_action(object sender, RoutedEventArgs e)
{
string _username = txtUser.Text;
string _password = txtPass.Password;
kollserviceClient client = new kollserviceClient();
client.validUserCredentialAsync(_username, _password);
client.validUserCredentialCompleted += Client_validUserCredentialCompleted;
client.isStudentUserAsync(_username);
client.isStudentUserCompleted += Client_isStudentUserCompleted;
}
private bool? isStudent = null;
private bool? isAuthenticated = null;
private void Client_isStudentUserCompleted(object sender, isStudentUserCompletedEventArgs e)
{
isStudent = e.Result;
EvaluateAndNavigate();
}
private void Client_validUserCredentialCompleted(object sender, validUserCredentialCompletedEventArgs e)
{
isAuthenticated = e.Result;
if (isAuthenticated)
{
IsolatedStorageSettings.ApplicationSettings["lgusername"] = txtUser.Text;
}
EvaluateAndNavigate();
}
private void EvaluateAndNavigate()
{
if(isStudent.HasValue && isAuthenticated.HasValue) //both calls have returned
{
if(isStudent.Value && isAuthenticated.Value)
{
NavigationService.Navigate(new Uri("/Home.xaml", UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show(string.Format("{0}Unable to Login", isStudent.Value ? "" : "User is Not a Student. " ), "Error", MessageBoxButton.OK);
}
}
}

Putting restrictions on deleting hashtable

I have a hashtable in my forms. So basically I have 2 button Add and Delete. When I put info in the textbox and add it adds it in the hashtable. But when I click delete it deletes it and when there's no value in it, it shows an error.
Question: So what I want to do is that when I put info in textBox1 which is not added in the Hashtable, it should give an error otherwise if the value is already added, it should just delete it.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" && b == "" || a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else
{
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void button4_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(textBox1.Text + "has been removed");
Info.Remove(a);
}
}
For example: If I add 2 in Hashtable and try to delete 3, it will still delete it just because there's some value in the textBox.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void AddToHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else if(Info.ContainsKey(a) || Info.ContainsKey(b))
{
MessageBox.Show("Hash table already contain this key");
}
else
{
Info.Add(a);
Info.Add(b);
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void DeleteFromHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(a + " has been removed");
Info.Remove(a);
}
else
{
MessageBox.Show(a + " is not part of the hash table");
}
//same check here for b
if (b == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(b)) // but this deletes it even if the value has not been added
{
MessageBox.Show(b + " has been removed");
Info.Remove(b);
}
else
{
MessageBox.Show(b + " is not part of the hash table");
}
}
I change the code a little bit. You miss some crucial things. Like check if the keys are already exist in the HashTable when you try to add them. If you try to add existing key exception will occur. Also I changed name of the methods, you miss to add the both text boxes in the hash table.

Login Code works for admin and user , but did not show error when login with wrong id or pass

I am creating a program for my final project , i have set-up a database , everything works fine , but the only thing i couldn't finish is the Login system.
Both Users and admin will log through the same form.
When i enter an admin id , it will login and say "hello admin" , and user the same.
but when i enter a non-existent id , it wouldn't show the error..
here's my code -
private void button1_Click(object sender, EventArgs e)
{
try
{
string userNameText = txtUser.Text;
string passwordText = txtPass.Text;
string isAdmin = "yes";
string isNotAdmin = "no";
if (!(string.IsNullOrEmpty(txtUser.Text)) && !(string.IsNullOrEmpty(txtPass.Text)))
{
SqlConnection SCScon = new SqlConnection();
SCScon.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
SqlCommand cmd = new SqlCommand("SELECT ISNULL(SCSID, '') AS SCSID, ISNULL(SCSPass,'') AS SCSPass, ISNULL(isAdmin,'') AS isAdmin FROM SCSID WHERE SCSID='" + txtUser.Text + "' and SCSPass='" + txtPass.Text + "'", SCScon);
SCScon.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
{
MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
_Adminform.Show();
this.Hide();
}
else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
{
MessageBox.Show("Welcome " + txtUser.Text , "User");
_userform.Show();
this.Hide();
}
else
{
MessageBox.Show("Wrong ID/Pass");
}
}'
}
}
catch (Exception ex)
{
MessageBox.Show("error2" + ex);
}
}
Problem : You are checking for invalid user inside the whle loop. loop enters when only required user is matched. so if invalid user credentials are given it will not enter the loop hence you could not see the Invalid User MessageBox.
Solution : you can check the dr.Read() return value, if it is true means it has row with the user (either admin or normal-user).
if(dr.Read())
{
if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
{
MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
_Adminform.Show();
this.Hide();
}
else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
{
MessageBox.Show("Welcome " + txtUser.Text , "User");
_userform.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong ID/Pass");
}
if the User name and password does not match, the line SqlDataReader dr = cmd.ExecuteReader(); returns no rows, so it will not enter the while(dr.Read()) and hence, will not enter the else inside while(dr.Read()).
You will need to put the MessageBox.Show("Wrong ID/Pass"); outside the while loop.
This is the code inside the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace LoginDialogForm
{
public partial class Login_Dialog_Form1 : Form
{
public Login_Dialog_Form1()
{
InitializeComponent();
}
private bool ValidateUsername()
{
//TODO: add code to validate User Name.
return true;
}
private bool ValidatePassword()
{
if (!ValidateUsername())
{
MessageBox.Show("Wrong Username", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
{
//TODO: add code to validate password.
if (false)
{
MessageBox.Show("Wrong Password", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
return true;
}
}
}
private void btnOk_Click(object sender, EventArgs e)
{
if (!ValidatePassword())
{
txtUserName.Clear();
txtPassword.Clear();
return;
}
else
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtUserName.Clear();
txtPassword.Clear();
this.Close();
}
}
This the controls and their relevant properties:
//
// btnOk
//
Name = "btnOk";
Text = "&Ok";
btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
DialogResult = System.Windows.Forms.DialogResult.Cancel;
Name = "btnCancel";
Text = "&Cancel";
btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtUserName
//
Name = "txtUserName";
//
// txtPassword
//
PasswordChar = '*';
Name = "txtPassword";
//
// label1
//
Name = "label1";
Text = "Username";
//
// label2
//
Name = "label2";
Text = "Password";
//
// LogoPictureBox
//
LogoPictureBox.Name = "LogoPictureBox";
LogoPictureBox.TabStop = false;
//
// LoginForm1
//
AcceptButton = this.btnOk;
CancelButton = this.btnCancel;
ControlBox = false;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
Name = "LoginForm1";
ShowInTaskbar = false;
StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
Text = "Login Form";
This the code to call the form:
private void Form1_Load(object sender, EventArgs e)
{
Login_Dialog_Form1 NewLogin = new Login_Dialog_Form1();
DialogResult Result = NewLogin.ShowDialog();
switch (Result)
{
case DialogResult.OK:
//do stuff
break;
case DialogResult.Cancel:
this.Close();
break;
}
}

Categories

Resources