Trouble calling a method from a class - c#

Can anybody help me with this?:
I'm trying call a method from a my class "numbers" to show that if the entered number is over 50, on button click a message box shows displaying "high" but if it's below 50 it displays "low".
I can't figure out what i'm doing wrong here.
This is the code from my class:
private int number;
private string getNumber(int num)
{
number = num;
return number.ToString();
}
public int numProperty
{
get { return number; }
set { number = value; }
}
public void isHighorlow()
{
if (number >=50)
{
}
else
{
return;
}
}
Note: the int "number" is property that gets it's value from a text box too.
& here is the code from my form:
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.numProperty = Convert.ToInt32(numberBOX.Text);
info.isHighorlow = Messagebox.Show = ("High");
}
I know that I've not added the "low" bit yet because i'm still trying to see how this works. Sorry if it seems confusing as i'm still learning c#.
I get the error message: cannot assign isHighorlow because it's part of a method group.
And I also realise it's much easier if I just do an if statement on the textbox, but I'm practising Classes and Methods so I'm trying to do it this way.
thanks.

I'm guessing you want something like this:
public string isHighorlow(int number)
{
if (number >=50)
{
return "High";
}
else
{
return "Low";
}
}
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
Messagebox.Show(info.isHighorlow(Convert.ToInt32(numberBOX.Text)))
}

IsHighOrLow should be as follows
public bool isHighorlow()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
And in button click
if (info.isHighorlow){
//say high
} else
{
// say low
}

isHighorLow is a method, not a property.
MessageBox.Show is a method.
Not sure what you are trying to do but it should be :
if(info.isHigh(Convert.ToInt32(numberBox.Text)))
Messagebox.Show("High");
else
Messagebox.Show("Low");
Meaning you have a method isHigh like so:
public bool isHigh()
{
return number>=50
}

(disclaimer: double check boolean and associated constants per C#)
isHighOrLow doesn't do anything at all. Perhaps this would be better:
public boolean isHigh()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
Or, more concisely:
public boolean isHigh()
{
return number >=50;
}
When you call it, this might be closer to what you need:
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.numProperty = Convert.ToInt32(numberBOX.Text);
if (info.isHigh())
{
Messagebox.Show("High");
}
else
{
Messagebox.Show("Low");
}
}

In your class you have defined void isHighorlow().
This means that you have a method that returns nothing.
Of course such method cannot be used on the left part of an expression like you have done.
Probably you want to write in your class
public bool isHighorlow()
{
if (number >=50)
{
return true;
}
else
{
return false;
}
}
in this way you declare a method that return True if the internal value is >= 50 or false otherwise.
Now, in your form you can use the method in this way
Messagebox.Show(info.isHighorlow() ? "High" : "Low");
However, if the requirement is simply to return a flag for true or false, it is better to use a read only property changing the class code in this way
public bool isHighorlow()
{
get
{
return (number >=50 ? true : false);
}
// No set, read only
}

Try to change your code this way:
private int _number;
private string GetNumber(int number)
{
_number = number;
return number .ToString();
}
public int Number
{
get { return _number; }
set { _number = value; }
}
public string IsHigh()
{
get { if (number >= 50) return true; }
}
numbers info = new numbers();
private void Btn_Click(object sender, EventArgs e)
{
info.Number = Convert.ToInt32(numberBOX.Text);
MessageBox.Show(info.IsHigh ? "High" : "Low");
}

Related

How to use user defined property in construction method for a winform?

I made a textbox that only accepts numbers and a "-" for negative numbers. I would like there to be an option to disable negative numbers.
In the constructor method I want to reference the allowNegatives bool that is defined properties editor and do different things depending on if it allows negatives values. I'm running into the problem that the 'allowNegatives' bool is always its default value in the constructor. If I reference it elsewhere it is the correct value.
Is there an way to get the assigned property value rather than the default value in the constructor?
public partial class ControlIntEntry : TextBox
{
private bool allowNegatives = false;
[Description("Allow negative values"), Category("Behavior")]
public bool AllowNegatives
{
get { return allowNegatives; }
set { allowNegatives = value; }
}
public ControlIntEntry()
{
// user sets AllowNegatives to true using properties editor
InitializeComponent();
Console.WriteLine(allowNegatives); // returns false
if (allowNegatives)
{
//do one thing
}
else
{
// do something else.
}
Task.Run(() => AfterConstructor()); // use for testing
}
private async Task AfterConstructor()
{
await Task.Delay(1000);
Console.WriteLine(allowNegatives); //returns true
}
}
Before you can assign a value to an instance property, the class should be instantiated, so first constructor will run and then you can assign property values.
That said, to have a better understanding of what is happening here, when you drop an instance of a control on your form at design time and set some of its properties, designer will generate a code like this:
private void InitializeComponent()
{
...
this.myControl1 = new MyControl();
...
//
// myControl1
//
this.myControl1.Location = new System.Drawing.Point(0, 0);
this.myControl1.Name = "myControl1";
this.myControl1.Size = new System.Drawing.Size(100, 22);
this.myControl1.MyProperty = true;
...
}
I believe it's now clear that what is happening here. You see first the constructor of your control will run, then later property values will be set.
To use property values to configure your object can put the logic inside the setter of the property:
private bool myProperty = false;
public bool MyProperty
{
get { return myProperty;}
set
{
myProperty = value;
// some logic here.
}
}
It's the most common scenario.
Another option is delaying the initializations to some time later, for example when the control handle is created by overriding OnHandleCreated or another suitable time.
// This is just an example, the event may not be a good one for your requirement
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// some logic here
}
Another option for complex initialization scenarios which may involve multiple properties, you can implement ISupportInitialize and put the logic inside EndInit:
public class MyControl : TextBox, ISupportInitialize
{
public void BeginInit()
{
}
public void EndInit()
{
// some logic here
}
}
Then when you drop an instance of the control on the form, this code will be generated in addition to the common code that I showed at beginning of this answer:
...
((System.ComponentModel.ISupportInitialize)(this.myControl1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
...
(I expect it's obvious now, that) All above options will run after running the constructor.
Putting that code in the setter worked
public partial class ControlIntEntry : TextBox
{
private bool allowNegatives = false;
[Description("Allow negative values"), Category("Behavior")]
public bool AllowNegatives
{
get { return allowNegatives; }
set
{
allowNegatives = value;
if (allowNegatives)
this.KeyPress += KeyPress_AllowNegatives;
else
this.KeyPress += KeyPress_PositiveOnly;
}
}
public ControlIntEntry()
{
InitializeComponent();
}
private void KeyPress_PositiveOnly(object sender, KeyPressEventArgs e)
{
Char newChar = e.KeyChar;
if (!Char.IsDigit(newChar) && newChar != 8)
{
e.Handled = true;
}
}
private void KeyPress_AllowNegatives(object sender, KeyPressEventArgs e)
{
Char newChar = e.KeyChar;
int cursorIndex = this.SelectionStart;
if (cursorIndex == 0)
{
if (!Char.IsDigit(newChar) && newChar != 8 && newChar != 45)
{
e.Handled = true;
}
}
else
{
if (!Char.IsDigit(newChar) && newChar != 8)
{
e.Handled = true;
}
}
}
}

Why is my division operation returning 0?

this is my first question on this website, thanks for helping. I have a web application I'm trying to make, but it always returns 0 whenever I do a division operation. The end goal is to get the correct output and display it to my label on my webpage, and whenever I do a simple operation for testing, like 1+2, it is correct. Here's some code, this first block refers to the webpage logic itself.
public partial class Length : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
Conversion convertObj = new Conversion();
double userIntLength = double.Parse(txtLengthInput.Text);
double convertedLength = convertObj.Length;
lblResult.Text = convertedLength.ToString();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLength.SelectedIndex == 1)
{
lblUnits.Text = "Miles";
}
if (ddlLength.SelectedIndex == 2)
{
lblUnits.Text = "Kilometers";
}
if (ddlLength.SelectedIndex == 3)
{
lblUnits.Text = "Feet";
}
if (ddlLength.SelectedIndex == 4)
{
lblUnits.Text = "Yard";
}
if (ddlLength.SelectedIndex == 5)
{
lblUnits.Text = "Centimeters";
}
if (ddlLength.SelectedIndex == 6)
{
lblUnits.Text = "Inches";
}
}
}
Here is the business layer logic, and also where I think the issue is.
public class Conversion
{
double length;
public double Length
{
get
{
double total = (((double) length) / 1.609344);
return total;
}
set
{
length = value;
}
}
}
Doing some google-fu, everyone says it's because of the data types, but everything is casted into double so I'm not sure why that is happening.
You are never actually setting the length value in the Conversion class, if defaults to 0, so the answer will always be 0
You never assign a value to Conversion.Length property, so the Conversion.length field value is 0 and 0 / 1.609344 is still 0.
You may change your code to
Conversion convertObj = new Conversion();
convertObj.Length = double.Parse(txtLengthInput.Text);
double convertedLength = convertObj.Length;
BTW
In the Length getter you cast the length field to double although it is already decalred as double. So this is useless, and you can simply write
public class Conversion
{
double length;
public double Length
{
get
{
double total = length / 1.609344;
return total;
}
set
{
length = value;
}
}
}

Method not passing result back to main program

Having some real trouble understanding where I've gone wrong here. I've marked in the code what and where. I am using an XAML interface and do have objects for everything here. The code compiles but the TextBlock will not update with the result from updateVTCShortCode Thanks for the help!
MAIN PROGRAM
namespace VTCPT
{
/// <summary>
///
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
if (String.IsNullOrEmpty(display.finalResult()))
{ shortFormCodec.Text = ".."; }
else { shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
} /////THIS IS NOT ACTUALLY GETTING A RETURN
}
public void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void updateShortForm(object sender, SelectionChangedEventArgs e)
{
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void fsSiteBuild_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void updateSiteBuild(object sender, TextChangedEventArgs e)
{
int index = fsRoomDesig.Text.IndexOf(".");
if (index > 0)
{ fsSiteBuild.Text = fsRoomDesig.Text.Substring(0, index); }
else { fsSiteBuild.Text = ".."; }
}
private void vtcSystemName_SelectionChanged(object sender, RoutedEventArgs e)
{
}
}
}
updateVTCShortCode CLASS
namespace VTCPT
{
class updateVTCShortCode
{
String result = "";
public void mergeShortCode(String longFormCodec)
{ if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
}
public String finalResult()
{ return result; } //////SHOULD BE GETTING SENT BACK TO MAIN PROGRAM
}
}
I think the problem is that in the following code taken from your shortFormCodec_SelectionChanged method. You set shortFormCodec.Text = display.finalResult(); immediately followed by shortFormCodec.Text = "test";. The final result will never be visible because it is being immediately overwritten with "test".
if (String.IsNullOrEmpty(display.finalResult()))
{
shortFormCodec.Text = "..";
}
else
{
shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
}
As TheGeneral suggested in the comments, you should be able to identify this using breakpoints and stepping through the code (using the F8 key) while watching the values of your variables and text fields. If you hover your mouse over the variables and the .Text section of any shortFormCodec.Text line it will show you its value at that point in the program.
However, I think you may find it helpful if you adjust your code to use an if {} else if {} else {} structure. I would also change the finalResult() method to a property as it's doing nothing but return a string. For example:
class updateVTCShortCode
{
// You could set the default value to an empty string I.e. = ""
// but having it set to "Not set" may help you spot any problems for now.
// As long as you remember to call mergeShortCode() first, you would never
// see "Not set" returned anyway. But this would help you spot that mistake.
public string FinalResult { get; set; } = "Not set";
public void mergeShortCode(String longFormCodec)
{
if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
} else
{
// If longFormCodec is not matched, set the result to ".."
FinalResult = "..";
}
}
By setting the final result to ".." in the else block of the mergeShortCode() method and setting a default value for the FinalResult property (even if it is an empty string I.e. ""). You are preventing FinalResult ever being null and providing all possible outcomes from the one function. This means you can simplify the shortFormCodec_SelectionChanged() method to the following and easily reuse the mergeShortCode() method elsewhere:
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
shortFormCodec.Text = display.FinalResult;
}
}

No overload for method '' takes 1 argument

Well, my issue here is basically what it says in the title. I'm trying to call my bool value of my Player2 class for my Tic Tac Toe-project we have in school. I think it's worth mentioning that I use "Player Player1, Player2;" in the beginning of Form1.cs to create two instances of my class, Player. I've read multiple posts on the internet about this but all of them are people trying to call in more parameters than that they are providing. I don't see how a bool value of true or false is more than one.
Thanks in advance.
One of my buttons where this problem appears.
public void Btn1_Click(object sender, EventArgs e) >{
{
if (click1 == 0)
{
if (Player2.GetActive(true))//(turn == 0)
{
Btn1.Text = "X";
}
else
{
>Btn1.Text = "O";
}
//turn++;
click1++;
}
else
{
Btn1.Text = Btn1.Text;
}
display();
checkit();
}
}
This is my player class.
` public class Player
{
//Characteristics
string name;
int points;
bool Active;
//Constructor
public Player() { points = 0; Active = true; }
//Methods
public void SetName(string n) { name = n; }
public string GetName() { return name; }
public void SetPoints(int p) { points = p; }
public int GetPoints() { return points; }
public void SetActive(bool a) { Active = a; }
public bool GetActive() { return Active; }`
You have the code:
Player2.GetActive(true)
But you define get active as
public bool GetActive() { return Active; }`
So it is correct you have not defined a GetActive with a parameter.
Here,
if(Player2.GetActive(true))
you are passing an extra argument (true) to the method GetActive. As we can see from the method declaration of GetActive, it takes no parameters:
public bool GetActive() { return Active; }
// ↑
// empty parentheses
I think what you mean here is "if Player2.GetActive() is true..." right? You don't need to specify the value you want if it is true, just doing this is fine:
if (Player2.GetActive())
If you want to check if it is false, add ! before the call to negate the result:
if (!Player2.GetActive())
Like BugFinder said, you are using the method to get the Active-Value instead of using the method to set the value.
So change
Player2.GetActive(true)
to
Player2.SetActive(true)
Just as an addition:
Since we are working with C# here and many of your methods are called set and get, I suggest you change those methods to be properties:
public string Name
{
get { return name; }
set { name = value; }
}
public int Points
{
get { return points; }
set { points = value; }
}
public bool Active
{
get { return active; }
set { active = value; }
}
Now when you want to set the value, you can type
Player2.IsActive = true;
and to check the value simple type code like
If(Player2.IsActive)
//Do Stuff

if statement in textbox error

Doing a gui project for course and ran into a problem with my code. I have to run a bool method that will test to make sure that the words "tropical or saltwater" are only entered in and return true if correct.
But im having problems with getting the if statement to match the string that i have given it in the expression.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private bool Fishtype()
{
if (txtFishType.Text == "Tropical" | "easy" )
{
return true;
}
else
{
return false;
}
}
private bool Fishsize()
{
if(txtFishSize >= 3 && txtFishSize <= 20)
{
return true;
}
else
{
return false;
}
}
}
I think you meant for your if statement to be:
if (txtFishType.Text == "Tropical" || txtFishType.Text == "saltwater" ) { return true; }

Categories

Resources