Hello everyone I am trying to make since of what I am doing wrong or maybe I am over thinking it again. I am trying to create a class and in the class I am calling 2 private variables such as num1 and num2. Then i create a public property that corresponds to num 1 and num2. Then after I create that I need to create a public overriable method called calculate and this will add the two variables together and returns the results. Then I have a add button that I have to add the code to the button that adds the two numbers and output the result to a messagebox.I have tried a couple different ways and I still am not getting it.
Here is code 1:
public abstract class CalulateValues
{
protected List<int> values = new List<int>();
public void AddValue(int value) { values.Add(value); }
public abstract int Calculate();
}
public class Add : CalulateValues
{
public override int Calculate()
{
return values.Sum(x => x);
}
}
and here is code 2 I tried:
class CalculateValues
{
private int _num1;
private int _num2;
public int Num1
{
get
{
return _num1;
}
set
{
_num1 = value;
}
}
public int Num2
{
get
{
return _num2;
}
set
{
_num2 = value;
}
}
public virtual int calculate()
{
return _num1 + _num2;
}
}
Now when it comes with the button I have tried this code:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
I am not too sure what I am doing wrong maybe I am not laying out the code the right way.
You have declared myAdd as a local variable in the Form2 constructor. Declare it as a global variable in order to be able to call it from button1_Click()
In addition to this, are you getting any error or exception? Second, where did you declare Add method that accepts two parameters?
public partial class Form2 : Form
{
CalculateValues myAdd;
public Form2()
{
InitializeComponent();
myAdd = new CalculateValues();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
}
And then go and look up firstly a C# tutorial, then look at detail on variable scope.
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
myAdd has no Add method at all. It is AddValue. And you should call Calculate and retrieve the result.
Declare myAdd as member variable instead local in constructor.
And try that:
myAdd.AddValue(int.Parse(textBox1.Text)
myAdd.AddValue(int.Parse(textBox2.Text);
int total = myAdd.Calculate();
MessageBox.Show(total.ToString());
Multiple bugs in your code.
You don't have a method Add, you shoudl use the method calculate like this
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
You need to declare the myAdd variable outside of the constructor, even if you only initialize in the Form2() constructor.
Your CalculateValues class does not have an "Add" method.
Instead you should be calling the "Calculate" method like this:
public partial class Form2 : Form
{
public Form2()
{
CalculateValues myAdd = new CalculateValues();
MulitplyValues Add = new MulitplyValues();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int total = myAdd.Calculate(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
MessageBox.Show(total.ToString());
}
Related
I'm learning the Windows Application Form in Visual Studio, I'm making a number guessing game where the program generates a random number.
I put the random number generator inside the Button_Click method, I want the number to say the same when the program start but it change every time I click the button.
public partial class myWindow : Form
{
public myWindow()
{
InitializeComponent();
}
private void guessButton_Click(object sender, EventArgs e)
{
Random random = new Random();
int roll = random.Next(0, 99);
Where should I declare or put the random number generator and variable so it doesn't change ?
Make it a class member:
public partial class myWindow : Form
{
private int _roll;
private int _numGuesses;
public Window()
{
InitializeComponent();
Random random = new Random();
_roll = random.Next(0, 99);
}
private void guessButton_Click(object sender, EventArgs e)
{
bool isGuessCorrect = // Set this however you need to
if (isGuessCorrect)
{
// They got it right!
}
else
{
_numGuesses++;
if (_numGuesses > 9)
{
// Tell them they failed
}
else
{
// Tell them they're wrong, but have 10 - _numGuesses guesses left
}
}
}
}
namespace LCB.Code
{
public class cuentaBanco
{
string nombre;
float cuenta;
public cuentaBanco(string nombre, float cuenta)
{
this.nombre = nombre;
this.cuenta = cuenta;
}
public void agregar(float incrementar)
{
this.cuenta += incrementar;
}
public void remover(float remover)
{
if (remover >this.cuenta)
{
this.cuenta = 0;
}
else
{
this.cuenta -= remover;
}
}
}
}
using LCB.Code;
namespace ACB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = cuentaBanco.agregar(float.Parse(textBox1.Text)).ToString();
}
}
}
An instance of an object is required this means that you cannot call a NON STATIC method of a class without having declared and initialized an instance of that class. So you have two options. Make the agregar method static or initialize an instance of the cuentaBanco class. I really suggest to stay away from static methods unless you have a clear reason to condivide the method between many instances of your class and in your code I can't see any reason to have a static method. So I am going for the other option.
Make an instance of the cuentaBanco class...
private void button1_Click(object sender, EventArgs e)
{
cuentaBanco cuenta = new cuentaBanco("ABC", 0f);
label1.Text = cuenta.agregar(float.Parse(textBox1.Text)).ToString();
}
but now we have another problem. The agregar method is declared as void. It means that it doesn't return anything. So you can't apply a ToString() to a void returning method.
You need also change the agregar method to return the calculated value
public class cuentaBanco
{
....
public float agregar(float incrementar)
{
this.cuenta += incrementar;
return this.cuenta;
}
....
}
Again, looking at your class it seems that you want to have an object that keeps your counting and increment the internal number for every click on your button. In this case you want to keep a global object for your counting and declare and initialize a class level variable of type cuentaBanco at the initialization of your form. Now you can use that variable to make your countings
public partial class Form1 : Form
{
private cuentaBanco cuenta;
public Form1()
{
InitializeComponent();
cuenta = new cuentaBanco("ABC", 0f);
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = cuenta.agregar(float.Parse(textBox1.Text)).ToString();
}
}
You should make method agregar static.
Also after making agregar static you should make cuenta static too. Also the agregar method is void you can't set it to label1.Text you should change it's return type yo float:
static float _cuenta;
public static float agregar(float incrementar)
{
_cuenta += incrementar;
return _cuenta;
}
Also in the cuentaBanco method remove the this keyword and set a valid name instead of cuenta like _cuenta:
public cuentaBanco(string nombre, float cuenta)
{
this.nombre = nombre;
_cuenta = cuenta;
}
This question already has answers here:
Call method on another form that is still open?
(2 answers)
Closed 9 years ago.
I create a form that contains a public field and a button. The button creates another form and shows it as dialog. Can I access to the public fields on main form? the main form run in main method like this:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
public partial class MainForm : Form
{
public int number;
public MainForm()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
(new SecondForm()).ShowDialog();
}
}
public partial class SecondForm : Form
{
public SecondForm()
{
InitializeComponent();
}
void Method()
{
//How can I access to number?
}
}
I don't want use constructor because there are a lot of variables in mainform.
You can use the ShowDialog Method that sets the owner of the created form.
secondForm.ShowDialog(this);
usage in your second form:
var temp = ((MainForm)this.Owner).number;
Create an object of the MainForm class and you can use it access all the public variables in the class
MainForm f = new MainForm();
int a = f.number;
This might not really work as it will create a new instance of the MainForm class and you might not get the desired result, so a better will be to make number static.
public static int number;
Then you can use
int a = MainForm.number;
Sure, just do:
var form = new SecondForm();
form.<property> = <value>
// ...
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
// ...
You said you don't want to use the SecondForm constructor to pass all of those variables from MainForm. Why not just create a class to hold the values and pass the class instance between the two?
public class FormData
{
public int number;
public int anotherInt;
public FormData(int num)
{
number = num;
}
}
public class SecondForm : Form
{
private FormData myData;
public SecondForm(FormData data)
{
myData = data;
}
}
public void AMethodInMainForm()
{
FormData d = new FormData(this.number);
d.anotherInt = 26;
SecondForm frm = new SecondForm(d);
}
Declare your number as public static int number and then:
public partial class SecondForm : Form
{
public SecondForm()
{
InitializeComponent();
}
void Method()
{
MainForm.number = // something
}
}
Define a public number in SecondForm
public int number;
Then before you show SecondForm try this:
SecondForm f2 = new SecondForm();
f2.number = this.number;
f2.ShowDialog();
Then you can access your number inside of your SecondForm.This works if you call number variable several times from your methods inside of your form2.But if you want access number in Form1 whenever you want,you should define it as Static and Public
I'm a new programmer to C# and I would like some help. I searched a lot but I didn't find a simple example. Please see the code below:
public partial class Welcome : Form
{
public Welcome()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
Compare comp = new Compare();
comp.Comparator();
}
}
In the Compare Class I have a simple method that contains a simple loop:
public class Compare
{
public void Comparator()
{
for (int i;i<val;i++)
{ /* ............. */ }
}
}
I want to update the ProgressBar in parallel with an increment of the value of i.
You said you searched a lot... where? These are most trivial things with very well described examples in MSDN
in BackgroundWorker_doWork method:
Parallel.For(0, val, i =>
{
...
backgroundWorker.ReportProgress(0);
});
in BackgroundWorker_reportProgress method:
wf.progressBar.Value=wf.progressBar.Value + 1;
in Main form constructor
public Welcome()
{
InitializeComponent();
Compare.wf=this;
}
in
public class Compare
{
static Welcome wf;
public void Comparator()
{
backgroundWorker.RunWorkerAsync();
}
}
A simple way of doing that is:
public class Compare
{
public void Comparator()
{
progressBar.Value = 0;
progressBar.Maximum = val;
progressBar.Step = 1;
for (int i;i<val;i++)
{
/* ............. */
progressBar.PerformStep();
}
}
}
Specifically looking at the arrive method in the Customer class. I am using a for loop to create instances of the customer class, and when I try to write out their arrival times to a textBox (Just for testing purposes) the text box does not update. Why is this?
This is just a small simulation project for my Computing class. It is in its early stages, and is probably wrong in a lot of places!
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 System.Threading;
namespace QueueSimulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("The form has loaded");
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
Customer customer = new Customer();
customer.Arrive();
}
private void stopButton_Click(object sender, EventArgs e)
{
// put code here to break out of the program
}
}
public class Customer : Initialisers
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
Initialisers init = new Initialisers();
public void Arrive()
{
Customer[] customer = new Customer[1000];
int counter = 0;
for (int i = 1; i <= 10; i++)
{
customer[i] = new Customer();
customer[i].TimeArrived();
displayArrival.Text = displayArrival.Text + customer[i].TimeArrived().ToString();
// Implement something to either show the time in the queue if needed
Thread.Sleep(init.CustomerArriveTime*100);
}
MessageBox.Show("All of the customers have arrived");
}
public string TimeArrived()
{
return Convert.ToString(DateTime.Now);
}
public void Leave()
{
}
public void GetServed()
{
}
}
public class Server
{
bool servingStatus;
int servingTime;
public void Serve()
{
}
}
public class Initialisers : Form1
{
private int cust_no = 3;
public int CustomerArriveTime
{
get
{
return cust_no;
}
set
{
cust_no = value;
}
}
private int s_time = 4;
public int serveTime
{
get
{
return s_time;
}
set
{
s_time = value;
}
}
}
}
Pass to the Arrive the instance of the textbox object created on your Form1.
public void Arrive(TextBox displayArrival)
Why are you inheriting the Form1 in Initialiserz? It's better to pass the reference to Form1 instead of inheritance in this case.
This seems overly complex. Try to model the real world. What is Initialisers, and why do you have an inheritance tree: Customer > Initialisers > Form1?
You're customer is writing to its own TextBox, instead of the TextBox you're looking at (the one from the Form that is visible).
Why not have a method Arrive that sets a private field to DateTime.Now. Then, ask the Customer its TimeArrived, which returns this field. In your Form, call these methods as much as needed in your loop.
This also seperaties command (Arrive) from query (TimeArrived) + keeps your inheritance more logical.
You might not even need Initialisers anymore. And don't let Customer inherit from Form, because a Customer isn't a Form.
I think there is more of a design issue here, you are creating instances of customer inside customer.
Your customer Arrive method should probably be a function inside the another class, like below, customer should just define what a customer is. Processing them should be handled by a different class.
class Customer
{
int waitingTime;
int arrivalTime;
int arrivalInterval;
// etc...
}
class ProcessCustomers
{
pubic void Arrive()
{
// etc...
}
}
public void goButton_Click(object sender, EventArgs e)
{
Initialisers init = new Initialisers();
ProcessCustomers CustomerQueue = new ProcessCustomers();
CustomerQueue .Arrive();
}
But for the text box issue you will have to expose a property in the form class and set it like that,
string ArrivalTime
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}