I have tried to get the textbox.text to a class and it doesent work what am I am doing wrong please help!
In my form.cs it looks like this:
public string score1;
public void getPlayerOneScore1Input()
{
score1 = playerOneScore1TextBox.Text;
}
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
score1Calculator theCalculator = new score1Calculator(score1);
}
and in my CLASS it looks like this:
class score1Calculator
{
public score1Calculator(string score1)
{
this.score1= score1;
}
public int playerOneDart1Value;
public void calculateDart1()
{
if (score1== "t1" || score1== "T1" || score1== "3")
{
playerOneDart1Value = 3;
}
else
{
MessageBox.Show("Dart 1! This is not a valid input!");
return;
}
}
}
error i get:
'WindowsFormApplication1.score1Calculator' does not contain a definition for 'player' and no extension method 'player' accepting a first argument of type 'WindowsFormApplication1.score1Calculator' could be found (are you missing a using directive or an assembly reference?)
There is no need to do it overly complicated. A Textbox.Text value is just a string. You can directly call the constructor with this reference.
Just write it like this
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
No need to store the value on module level.
you dont call getPlayerOneScore1Input() in order the score1 to be assigned, in Form1 try:
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
On button click you are not calling your function getPlayerOneScore1Input() which actually assign value to score1.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
Instead of assigning value to score1 in form class and assign it to your class member field. You may try this.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(playerOneScore1TextBox.Text))
{
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
}
}
Related
I am trying to carry the variables from the array over to the button click action. I can't find the way to set the scope to allow for this to work.
I have tried changing the modifiers to public, private, static, void, string, string[] etc.
I have also made all of the objects in the WinForms app set to Public
public partial class AutoPay : Form
{
public AutoPay()
{
InitializeComponent();
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
dateAndTime = DateTime.Now.ToString();
fileNumber = txtFileNumber.Text;
string[] headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(headerArray[0], headerArray[1]);
}
}
the headerArray[0] under the BtnSave_Click action has the red line under it showing that it is outside of the scope.
Try declaring the headerArray as a Property of the class
As was mentioned... you need to declare the headerArray outside the method... Also... it looks like you are trying to add information to the array before the array has information... try it this way(there are many other ways to do this too ;) ):
public partial class AutoPay : Form
{
private string[] headerArray; // <-- declare it here...
public AutoPay()
{
InitializeComponent();
headerArray = new string[2]; // <-- sometimes the normal way to initialize...
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(DateTime.Now.ToString(), txtFileNumber.Text);
}
}
or
public void HeaderInformation()
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = DateTime.Now.ToString();
headerArray[1] = txtFileNumber.Text;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation();
}
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;
}
I have to called a method Run in the Class1. And now I try to return str to listbox Running. I know this code Running.Items.Add(str); is not correct because it is in a different class. Please tell me how to fix it?
Class1.cs
class Class1
{
public void Run()
{
string str = "Hello";
Running.Items.Add(str);
}
}
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Running_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Update How do I call a class method
Form1
public void Invoke(string typeName, string methodName)
{
Type type = Type.GetType(typeName);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
method.Invoke(instance, null);
}
private void Start_Click(object sender, EventArgs e)
{
new Task(() => { Invoke("Worker." + name, "Run"); }).Start();
}
You don't show how you call Run(), so I'm going to assume you do so from Form1.
You need to pass a reference one way or the other. Making your class Class1 dependent on your form is a bad idea. You can make it dependent on the lsitbox, and rename it accordingly:
public class ListBoxAdder()
{
private ListBox _listBox;
public ListBoxAdder(ListBox listBox)
{
_listBox = listBox;
}
public void Run()
{
string str = "Hello";
_listbox.Items.Add(str);
}
}
Then call it from your form and pass the reference to the Running ListBox:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var listBoxAdder = new ListBoxAdder(this.Running);
listBoxAdder.Run();
}
}
If you want to add the str object to the Running list in the class class1 you should just get a reference to the active form of the Form1 :
public void Run()
{
string str = "Hello";
((Form1)Form1.ActiveForm).Running.Items.Add(str);
}
i'm learning how to use custom events in c#, but i get some errors
i get "An object reference is required for the nonstatic field, method, or property" in the bold words
so i tried following this
but case 1 couldn't be tried 'cause TypeChanged is already a nonstatic method (i think)
in case 2 i get "impossible to acces BicycleType as an instance reference, qualify it as a type"
public class Bicycle
{
public event EventHandler TypeChanged;
private string type;
...
public string BicycleType {
get { return this.type; }
set {
this.type = value;
if (this.TypeChanged != null)
this.TypeChanged( this, new EventArgs() );
}
}
public Bicycle() {}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("heila!");
Bicycle istanza = new Bicycle();
istanza.TypeChanged += new EventHandler(**istanza_TypeChanged**);
istanza.BicycleType = "io";
Console.WriteLine("io");
}
void istanza_TypeChanged(object sender, EventArgs e) {
Console.WriteLine("rofkd");
}
}
the tutorial i followed told me i can use events "as" methods, maybe i'm wrong here?
the code is completely similar to te tutorial code
sorry for my bad english and thanks in advance
As you are registering the event from the main method, which is static, the event handler (istanza_TypeChanged) has to be made static too.
You problem is that Main is static and can therefore not access nonstatic members of the class Program. However you try to access istanza_TypeChanged. That is what is causing your exception.
You have to make istanza_TypeChanged static too to solve the issue
class Program
{
static void Main(string[] args)
{
Console.WriteLine("heila!");
Bicycle istanza = new Bicycle();
istanza.TypeChanged += new EventHandler(**istanza_TypeChanged**);
istanza.BicycleType = "io";
Console.WriteLine("io");
}
static void istanza_TypeChanged(object sender, EventArgs e)
{
Console.WriteLine("rofkd");
}
}
Register the event from a non-static context or change your event to be static.
Change istanza_TypeChanged to the following:
private static void istanza_TypeChanged(object sender, EventArgs e)
{
Console.WriteLine("rofkd");
}
The following fired the event for me:
public class Bicycle
{
public event EventHandler TypeChanged;
private string type;
public string BicycleType
{
get { return this.type; }
set
{
this.type = value;
if (this.TypeChanged != null)
this.TypeChanged(this, new EventArgs());
}
}
public Bicycle()
{
}
private class Program
{
private static void Main(string[] args)
{
Console.WriteLine("heila!");
Bicycle istanza = new Bicycle();
istanza.TypeChanged += istanza_TypeChanged;
istanza.BicycleType = "io";
Console.WriteLine("io");
}
private static void istanza_TypeChanged(object sender, EventArgs e)
{
Console.WriteLine("rofkd");
}
}
}
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());
}