populating listbox from textbox - c#

I am trying to get the name of the Investment to appear in the listbox for stock but the code(which I used earlier in the program) doesn't seem to work.
namespace JamesClemens_FinalProject
{
public partial class Form1 : Form
{
ArrayList account;
public Form1()
{
InitializeComponent();
account = new ArrayList();
}
//here we set up our add customer button from the first tab
//when the information is filled in and the button is clicked
//the name on the account will be put in the combobox on the second tab
private void btnAddCustomer_Click(object sender, EventArgs e)
{
try
{
CustomerAccount aCustomerAccount = new CustomerAccount(txtAccountNumber.Text, txtCustomerName.Text,
txtCustomerAddress.Text, txtPhoneNumber.Text);
account.Add(aCustomerAccount);
cboClients.Items.Add(aCustomerAccount.GetCustomerName());
ClearText();
}
catch (Exception)
{
MessageBox.Show("Make sure every text box is filled in!", "Error", MessageBoxButtons.OK);
}
}
private void ClearText()
{
txtAccountNumber.Clear();
txtCustomerName.Clear();
txtCustomerAddress.Clear();
txtPhoneNumber.Clear();
}
private void cboClients_SelectedIndexChanged(object sender, EventArgs e)
{
CustomerAccount custAccount = account[cboClients.SelectedIndex] as CustomerAccount;
if(custAccount != null)
{
txtAccountNumberTab2.Text = custAccount.GetAccountNumber();
txtCustomerNameTab2.Text = custAccount.GetCustomerName();
txtCustomerAddressTab2.Text = custAccount.GetCustomerAddress();
txtCustomerPhoneNumberTab2.Text = custAccount.GetCustomerPhoneNo();
}
}
This is the code giving me trouble, it keeps saying that "new Stock" does not contain a constructor that takes four arguments.
private void btnAddStock_Click(object sender, EventArgs e)
{
try
{
Stock aStock = new Stock(txtInvestmentID.Text, txtInvestmentName.Text, txtInvestmentSymbol.Text,
int.Parse(txtInvestmentShares.Text));
account.Add(aStock);
lstStock.Items.Add(aStock.GetInvestmentName());
ClearText();
}
catch (Exception)
{
MessageBox.Show("Make sure every text box is filled in!", "Error", MessageBoxButtons.OK);
}
}
does anyone know why it's not letting me use the Stock class?
Here's the stock class like you asked for.
public class Stock:Investment
{
//attributes
private double stockPrice;
//constructors
public Stock()
{
}
public Stock(string anInvestmentID, string anInvestmentName, string anInvestmentSymbol,
int anInvestmentShare, CustomerAccount aCustomer, double aStockPrice)
: base(anInvestmentID, anInvestmentName, anInvestmentSymbol, anInvestmentShare)
{
SetStockPrice(aStockPrice);
}
//
public Stock(string anInvestmentID, string anInvestmentName, string anInvestmentSymbol,
int anInvestmentShare, CustomerAccount aCustomer, double aStockPrice)
{
SetInvestmentID(anInvestmentID);
SetInvestmentName(anInvestmentName);
SetInvestmentSymbol(anInvestmentSymbol);
SetInvestmentShare(anInvestmentShare);
SetStockPrice(aStockPrice);
}
//set accessors
public void SetStockPrice(double aStockPrice)
{
stockPrice = aStockPrice;
}
//get accessors
public double GetStockPrice()
{
return stockPrice;
}

Please actually read the error messages you get; it makes programming much easier.
The error message is pretty clear:
"new Stock" does not contain a constructor that takes four arguments.
You don't have a constructor in your Stock class that takes four arguments.
Look at the three constructors you posted in your Stock class. Count the number of parameters you need to pass into each constructor. Is there one that accepts four arguments only? I see one that takes no arguments, and two that each take six arguments.
Trying to understand the actual text of error messages will help you a lot in the future writing code. Most (not all, but most) error messages have meaningful content that points you to the actual problem. :)

Related

c# there is no argument given that corresponds to the required formal parameter

I'm kind of new to C# and i don't really know if I'm doing this correctly. So i have two forms, one of creating a character and one for the main game that I'm making. I have a two radio buttons to choose a character gender on one form. Now i want to pass whatever gender the user chose as text onto a label on the main game form.
On my CharacterCreation form i have created the following method:
public string characterGender(string Male, string Female, int id)
{
String genderFemale = Female;
String genderMale = Male;
int ID = id;
if (radiobtngenderFemale.Checked == true)
{
id = 1;
return Female;
}
else if (radiobtngenderMale.Checked == true)
{
id = 2;
return Male;
}
}
On my main game form i have the following code:
public partial class MainGame : Form
{
private CharacterCreation _characterCreation;
public MainGame()
{
InitializeComponent();
_characterCreation = new CharacterCreation();
lbl1.Text = _characterCreation.characterGender()
}
private void MainGame_Load(object sender, EventArgs e)
{
}
}
However I'm getting an error:
"There is no argument given that corresponds to the required formal parameter"
I've looked at a lot of other topics but couldn't really find an answer.
When you are calling the method _characterCreation.characterGender()
You need to pass the declared parameters.
Or remove the parameters from your method
characterGender(string Male, string Female, int id)
To
characterGender()

How to pass through data from a child form into the parent form without refreshing the list

I am doing a school project in creating a POS system and i need to pass in through the same order list throughout the different form.The problem is everytime i return to the main menu, the list refreshes although i still need the data is there anyway to prevent this from happening?
public partial class Main : Form
{
List<string> order = new List<string>();
public Main()
{
InitializeComponent();
}
public Main(List<string> order)
{
InitializeComponent();
this.order = order;
}
this is the start code for the main menu
And this is the code to add the items from thelistbox to the list
private void confirmbtn_Click(object sender, EventArgs e)
{
order.AddRange(temp_order);
if (pendinglist.Items.Count != 0)
{
MessageBox.Show("Your Items have been added! yay!", "That Sushi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No items was selected.", "That Sushi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
pendinglist.Items.Clear();
}
Thank you in advance for your help.Please let me know if anything else is wrong with the code too. again thank you for the help
You are probably closing the form and re-creating it every time you open it again, and since these orders are inside it, obviously the previous content is lost.
Solution : that list of orders should be outside main form
Here's a really simple pattern for you, it's really primitive but it works and should be enough/plausible for your homework : a static class
public static class MyModel
{
public static Order Order { get; set; }
public static void NewOrder()
{
Order = new Order();
}
}
public class Order
{
public Order()
{
Products = new List<Product>();
}
public List<Product> Products { get; set; }
public void AddProduct(Product product)
{
Products.Add(product);
}
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
And here's how you'd use it from a form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonNewOrder_Click(object sender, EventArgs e)
{
MyModel.NewOrder();
}
private void buttonAddProduct_Click(object sender, EventArgs e)
{
var product = new Product();
product.Name = "PS4";
product.Price = 1000000000.0m;
MyModel.Order.AddProduct(product);
}
private void buttonShowProductsInOrder_Click(object sender, EventArgs e)
{
var order = MyModel.Order;
var products = order.Products;
var builder = new StringBuilder();
foreach (var product in products)
{
var format = string.Format("Name: {0}, Price: {1}", product.Name, product.Price);
builder.AppendLine(format);
}
MessageBox.Show(builder.ToString());
}
}
Order will not vanish and will be accessible from many forms.
Obviously it's a pretty bad practice, gurus would use MVP (model view presenter), MVC (model view controller) or whatever pattern along a database behind, but there's little point to roll out such design for your question. You can/should take a look at what these concepts are, however.
Good luck !

C# assign textbox value to a variable in another class in another file

I have created a simple form "people" and there is another file "Information.cs"
In main for assign text box "txt_lname" value to a variable
String lastname = txt_lname.Text;
Then I want to use this value within "information class" (It is a thread class)
How can I use it ?
(I have commented the place I wanted to use that value)
Main Form
namespace users
{
public partial class people : Form
{
public people()
{
InitializeComponent();
}
private void btn_login_Click(object sender, EventArgs e)
{
String lastname = txt_lname.Text;
}
}
}
Information Class
namespace users
{
class Information
{
int[] idno = new int[10];
int[] age = new int[10];
string[] fname = new string[10];
// Here I want to assign txt_lname.Text value to a variable
lastname = txt_lname.Text; // This code is not working
public void run()
{
while (true)
{
for (int i = 0; i < 600; i++)
{
//Some code here
try
{
Thread.Sleep(100);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
}
}
}
}
}
* Can I use value of a variable within run method in thread class ? if cannot then why ?
You have to create an instance of Information on your form and then pass the data to said instance. A classes' code won't magically be executed just because you added it to your project, you have to actually create an instance of the class.
So lets create and initialize an instance of Information on the form:
public partial class people : Form
{
private Information _information;
public people() {
InitializeComponent();
_information = new Information();
}
}
You can now pass stuff to your instance of Information. But to do that you need a way to pass it, or in this case Information needs a way to receive a LastName. There's more than one way to do this but a common approach is to expose a LastName property on Information:
public class Information
{
...
public string LastName { get; set; }
...
}
And now you can pass the value to the LastName property:
private void btn_login_Click(object sender, EventArgs e) {
_information.LastName = txt_lname.Text;
}
Note: When you want to execute the run method on Information you'll do it through the instance just like when you're setting the LastName:
private void btn_run_click(object sender, EventArgs e) {
_information.run();
}
Make the Information class Static
public static class Information
And in your main form you can use it like
Information.LastName = txt_lname.Text;
But you also need to declare LastName as property. So add
public string LastName {get; set;}
into your Information Class.

WPF and C#: Trouble with Classes and Interfaces

I'm working on a bank account program. I'm using a base class, an interface, and two derived classes in addition to my main window class. I am making a WPF application, and so far I am able to populate a ListBox with an ArrayList of class objects in that app just fine. However, when I go to modify any of the objects in the ArrayList, I'm running into difficulty repopulating the ListBox correctly. Any help will be greatly appreciated!
This is my MainWindow code:
public partial class MainWindow : Window
{
ArrayList bankAccountList = new ArrayList();
BankAccount savingsAccount = new SavingsAccount("New", "Account", "newaccount");
BankAccount checkingAccount = new CheckingAccount("New", "Account", "newaccount");
IAccount iAccount;
string typeOfAccount = "";
public MainWindow()
{
InitializeComponent();
}
//When the user pushes the "Add A Saving Account" button, a new savings account is added to the ArrayList and displayed in the app.
private void btnAddAccount_Click(object sender, RoutedEventArgs e)
{
iAccount = (IAccount)savingsAccount;
savingsAccount.Deposit(0.00m);
bankAccountList.Add(savingsAccount);
lbxExistingAccounts.Items.Add(iAccount.AccountInformation());
typeOfAccount = "savings";
}
//When the user pushes the "Add A Checking Account" button, a new checking account is added to the ArrayList and displayed in the app.
private void btnAddCheckingAccount_Click(object sender, RoutedEventArgs e)
{
iAccount = (IAccount)checkingAccount;
checkingAccount.Deposit(0.00m);
bankAccountList.Add(checkingAccount);
lbxExistingAccounts.Items.Add(iAccount.AccountInformation());
typeOfAccount = "checking";
}
//When the user pushes the "Delete Account" button, the account is removed, and this change is shown in the app.
private void btnDeleteAccount_Click(object sender, RoutedEventArgs e)
{
lbxExistingAccounts.Items.RemoveAt(lbxExistingAccounts.Items.IndexOf(lbxExistingAccounts.SelectedItem));
}
//The user can push the "Submit Changes" button to submit his or her changes to the number and name of the account.
private void btnSubmitChanges_Click(object sender, RoutedEventArgs e)
{
try
{
for (int index = 0; index < bankAccountList.Count; index++)
{
if (index == lbxExistingAccounts.SelectedIndex)
{
if (typeOfAccount == "savings")
{
savingsAccount.AccountNumber = tbxAccountNumber.Text;
savingsAccount.AccountOwnerFirstName = tbxFirstName.Text;
savingsAccount.AccountOwnerLastName = tbxLastName.Text;
}
else if (typeOfAccount == "checking")
{
checkingAccount.AccountNumber = tbxAccountNumber.Text;
checkingAccount.AccountOwnerFirstName = tbxFirstName.Text;
checkingAccount.AccountOwnerLastName = tbxLastName.Text;
}
}
}
lbxExistingAccounts.Items.Clear();
foreach (object accountObject in bankAccountList)
{
lbxExistingAccounts.Items.Add(accountObject);
}
}
catch (FormatException)
{
MessageBox.Show("You may enter changes as letters, numbers, or both.");
}
}
This is my Interface code:
interface IAccount
{
void SetAccountBalance(decimal accountBalance);
string AccountInformation();
}
This is my base class code:
abstract class BankAccount
{
public string AccountNumber { get; set; }
public string AccountOwnerFirstName { get; set; }
public string AccountOwnerLastName { get; set; }
public decimal AccountBalance { get; set; }
public decimal AnnualInteresetRate { get; set; }
public string TypeOfAccount { get; set; }
public BankAccount(string accountOwnerFirstName, string accountOwnerLastName, string accountNumber)
{
AccountOwnerFirstName = accountOwnerFirstName;
AccountOwnerLastName = accountOwnerLastName;
AccountNumber = accountNumber;
}
public abstract void Deposit(decimal amount);
public abstract void Withdraw(decimal amount);
public decimal CalculateInterest()
{
return (this.AccountBalance * this.AnnualInteresetRate) / 100;
}
}
This is one of my derived classes. I made both pretty much the same.
class SavingsAccount : BankAccount, IAccount
{
public SavingsAccount(string accountOwnerFirstName, string accountOwnerLastName, string accountNumber)
: base(accountOwnerFirstName, accountOwnerLastName, accountNumber)
{
AnnualInteresetRate = 0.95m;
}
public override void Deposit(decimal amount)
{
AccountBalance = AccountBalance + amount;
}
public override void Withdraw(decimal amount)
{
AccountBalance = AccountBalance - amount;
}
public void SetAccountBalance(decimal accountBalance)
{
AccountBalance = accountBalance;
}
public string AccountInformation()
{
return "Savings Account \n " + AccountOwnerFirstName + " " + AccountOwnerLastName + ", Account#: " + AccountNumber + ", Balance: $" + AccountBalance;
}
}
It looks like you are just starting out, which is good, because you are going to want to rework some things.
You don't need to cast your derived objects to their base types. This type of casting is called "upcasting" and automatically works without any casting whatsoever.
The code you posted is highly "WinForms-ish" and this is not a good approach in WPF. Start with making your account list an ObservableCollection and binding your ListBox's ItemsSource to it.
The property would look like:
public ObservableCollection<BankAccount> Accounts {get; set;}
Which should actually use INotifyPropertyChanged omitted for brevity, and the binding:
<ListBox "ItemsSource={Binding Accounts}"/>
Of course, that should go in a view model class, but you could start with your code-behind by setting:
DataContext = this;
Once that is working all your text boxes should be bound to properties of the data objects or of the view itself.
Here is a great tutorial on using MVVM with WPF (MSDN). Trust me, using this design pattern will make your work with WPF immensely easier, more extensible, and you will find that WPF was basically designed to use it. Using a WinForms approach is just going to cause you pain.
Please let me know if I can assist further or clarify anything!
I would recommend using ObservableCollection for your collection, so that any changes made to the items would be reflected visually without any additional work. It wouldn't require any significant changes. All you would do is switch your ArrayList for an ObservableCollection.
http://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx
I would also highly recommend implementation of INotiftyPropertyChanged interfrace for your objects, so that when account information is changed, appropriate subscribers are notified.
http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged
I've been using both of those extensively with my WPF applications.

How to use same instance name with multiple classes

I'm new to c# and I think I want to do this but maybe I don't and don't know it!
I have a class called SyncJob. I want to be able to create an instance to backup files from My Documents (just an example). Then I'd like to create another instance of SyncJob to backup files in another folder. So, in other words, I could have multiple instances of the same class in memory.
I'm declaring the object var first in my code so it is accessible to all the methods below it.
My question is: while using the same instance name will create a new instance in memory for the object, how can I manage these objects? Meaning, if I want to set one of the properties how do I tell the compiler which instance to apply the change to?
As I said in the beginning, maybe this is the wrong scheme for managing multiple instances of the same class...maybe there is a better way.
Here is my prototype code:
Form1.cs
namespace Class_Demo
{
public partial class Form1 : Form
{
BMI patient; // public declarition
public Form1()
{
InitializeComponent();
}
private void btnCreateInstance1_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 1 Created", 11); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void displayInstanceName(BMI patient)
{
MessageBox.Show("Instance:"+patient.getName()+"\nwith Age:"+patient.getAge());
}
private void btnCreateInstance2_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 2 Created", 22); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void btnSetNameToJohn_Click(object sender, EventArgs e)
{
// this is the issue: which instance is being set and how can I control that?
// which instance of patient is being set?
patient.setName("John");
}
private void btnDisplayNameJohn_Click(object sender, EventArgs e)
{
// this is another issue: which instance is being displayed and how can I control that?
// which instance of patient is being displayed?
displayInstanceName(patient);
}
}
}
Class file:
namespace Class_Demo
{
class BMI
{
// Member variables
public string _newName { get; set; }
public int _newAge { get; set; }
// Default Constructor
public BMI() // default constructor name must be same as class name -- no void
{
_newName = "";
_newAge = 0;
}
// Overload constructor
public BMI(string name, int age)
{
_newName = name;
_newAge = age;
}
//Accessor methods/functions
public string getName()
{
return _newName;
}
public int getAge()
{
return _newAge;
}
public void setName(string name)
{
_newName = name;
}
}
}
You can have public List<BMI> PatientList { get; set; } instead of BMI patient;
if you have one patient you not sure which item accessing and when you assign it will replace previous one
public List<BMI> PatientList { get; set; }
public Form1()
{
InitializeComponent();
PatientList = new List<BMI>();
}
with list of BMI you can add items like below
PatientList.Add(new BMI("Instance 1 Created", 11));
PatientList.Add(new BMI("Instance 2 Created", 22));
if you need to set name of instance 1, you can get the item by index
PatientList[0].setName("John");
Or you can find the patient by one of the property by loop though the PatientList
if you need to display the patient details of "John", by using LINQ
displayInstanceName(PatientList.FirstOrDefault(p=>p.Name =="John"));
If you need to manage a collection of instances, use a List<BMI> or similar. The generic List<T> class can hold (almost) any type of object, is easy to work with, etc. It's also a vital part of the .NET toolkit that you will use many, many times.
Also, consider rewriting your BMI class to use properties more effectively:
class BMI
{
public string NewName { get; set; }
public int NewAge { get; protected set; }
public BMI()
: this("", 0)
{ }
public BMI(string name, int age)
{
NewName = name;
NewAge = age;
}
}
The accessor methods are not required unless you need them for interop with some other system. Using modifiers on the get and set accessors on the properties themselves you can make public-read/private-write properties, etc.

Categories