I have been given an assignment on C# window form where I get to calculate an input textbox from a user, the user wants to input a value and then presses a radiobutton(square root) then clicks a normal button to get the result. Is it possible to get the result in a textbox (instead of a label)? If so, how do I do that using 'methods' (linking methods to the button_click one)? Also, why do I need to return a parameter value of a method? it doesn't let me execute without returning ;/
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int square(int A)
{
if (rbSquare.Checked)
{
Math.Sqrt(A);
return Convert.ToInt32(Math.Sqrt(A));
}
else
{
return A;
}
}
private void btncalculate_Click(object sender, EventArgs e)
{
int firstNum = Convert.ToInt32(tbinput.Text);
int squareRoot = square(firstNum);
tbResult.Text = "" + squareRoot;
}
}
}
Is it possible to get the result in a textbox (instead of a label)?
Sure. Set the text property of the text box, just like you would set the label text of a label.
why do I need to return a value from a method?
You said that square returns an int always, but you only return an int if the checkbox is checked. The compiler is reminding you that you need to return an int always in order to fulfill the contract that you promised. What value should you return if the checkbox is not checked?
Related
I'm trying to create a Calculator with a Class. However using references from the internet particularly from this website (https://www.sourcecodester.com/tutorials/c/7548/simple-calculator-using-class-c.html)
It did not mention to declare "Information" or whatsoever.
When I typed in the code, the error list return with Information does not exist in current context.
Is there a way to modify the code below? Thank you so much.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
public void RadioButton_Click(object sender, System.EventArgs e)
{
//call a constructor method and return to cal as an instance of a class
calculate cal = new calculate();
//declaring the string variable represent as a textbox
string txtnum1 = TextBox1.Text;
string txtnum2 = TextBox2.Text;
//declaring the double variable
double dbl_val1 = default(double);
double dbl_val2 = default(double);
if (**Information**.IsNumeric(txtnum1) && **Information**.IsNumeric(txtnum2)) //check if the textbox has a numeric value
{
//convert the string to double
dbl_val1 = double.Parse(txtnum1);
dbl_val2 = double.Parse(txtnum2);
//get the value of the converted variable
//to pass it into the variable in the class
cal.num1 = dbl_val1;
cal.num2 = dbl_val2;
//the condition is, if the radiobutton is clicked,
//the operation of MDAS executes.
if (Radio_Multiplication.Checked)
{
//result:
cal.multiply(); //call a subname in a class for multiplying
}
else if (Radio_Addition.Checked)
{
//result:
cal.add(); //call a subname in a class for adding
}
else if (Radio_Subtraction.Checked)
{
//result:
cal.subtract(); //call a subname in a class for subtracting
}
}
else
{
//the result is:
//if the textbox is empty or has a string value
TextBox3.Text = "Enter a number";
return;
}
//put the result of the MDAS to a textbox.
TextBox3.Text = cal.total.ToString();
}
}
I had a quick look at the link and they don't appear to have declared Information anywhere nor have they indicated that they've overridden anything so...I don't know.
That line, however, is just validating that the information entered into the two text boxes are actually numbers and not anything else that can't be calculated.
There are lots of methods you could use to check those numbers. Options would include, but are not limited to:
if(Int32.TryParse(txtNum1, out int temp1) && Int32.TryParse(txtNum2, out int temp2))
{
do stuff;
}
or
if(txtNum1.All(char.IsDigit) && txtNum2.All(char.IsDigit))
{
do stuff;
}
There are other options, but those two might be worth looking into.
Downloading the sample project, I had a look at what Information refers to. Turns out, it's a class from the Microsoft.VisualBasic namespace, presumably for exposing certain aspects of the VB core library to all .NET languages. You can use it in your program by adding a reference to Microsoft.VisualBasic to your project and adding:
using Microsoft.VisualBasic;
to the top of your code file.
(Personally, I can't imagine that this approach is terribly efficient. It's supposed to take an object and determine if it can be evaluated as a number, and I have no idea what approaches it uses to make that deduction based on any random object. You would probably be better off using one of the alternatives that Benny O'Neill suggests.)
I have an application with four text boxes. I want user to be able to enter a value in the first three text boxes. The fourth will give the result (box1 + box2 + box3) / 3.
My textboxes look like this.
private void rBox_1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckIsNumber(e);
}
And a function to let user enter only digits.
private void CheckIsNumber (TextCompositionEventArgs e)
{
int result;
if (!int.TryParse(e.Text, out result))
{
e.Handled = true;
}
}
The problem is I don't know how to convert and store a value from each textbox in an int.
I've created a null int value to store. In public MainWindow().
int box1_value;
And for function I did this.
public static int GetNumber (string arg)
{
int number = Int32.Parse(arg);
return number;
}
When I'm trying to apply this function this way, nothing happens. Program won't start, no errors, though.
public MainWindow()
{
InitializeComponent();
int box1_value = GetNumber(rBox_1.Text);
}
Remove the
int box1_value = GetNumber(rBox_1.Text);
from your mainwindow constructor.
You're parsing a string.Empty value to int in which the compiler will automatically halt during compilation. Hence your awkward error.
Create a new function called Calculate for calculating your values
private void Calculate()
{
if(string.IsNullOrEmpty(rBox_1.Text) ||
string.IsNullOrEmpty(rBox_2.Text) ||
string.IsNullOrEmpty(rBox_3.Text))
return;
var box1 = GetNumber(rBox_1.Text);
var box2 = GetNumber(rBox_2.Text);
var box3 = GetNumber(rBox_3.Text);
rBox_4.Text = ((box1 + box2 + box3)/3).ToString();
}
You have 2 options for adding the Calculate function:
add it in each rBox_1_PreviewTextInput function as follows:
if(e.Handled)
{
Calculate();
}
or create a button (named button1)
private void button1_Click(object sender, EventArgs e)
{
Calculate();
}
Some Comments: why the string.IsNUllOrEmpty in Calculate?
-> Your GetNumber function does not catch any false string values like Empty. Or you work with tryparse in the GetNumber function or you catch the empty values before you go into the function.
Try using TryParse Method :
int number = Int32.Parse(arg); /*Instead of this line in your code use below.*/
A possible duplicate thread
I would Suggest that you should Add validation to your 1st 3 Test-boxes using PreviewTextInput in that way, you do not have to try parse int in your c# code and will reduce the chance of errors in your code
I am writing a c# windowsform application for addition of two entries in a single text box.
I have 1 text box, 1 add button and 1 result button.
I need to achieve following algo,
User enter the no in text box. It will be stored in int n1.
User will press add button. At this time the content of the textbox.text will be get cleared and user must be able to enter the secound value in it.
This secound value will get stored in int n2.
Now when user click on result button he should get int result=n1+n2
I have written following in add buttons's click event,
n1=convert.Int32(textbox1.text);
textbox1.text="";
n2=convert.Int32(textbox1.text);//exception occures here
And result button's click event has,
textbox1.text=result.tostring();
I leanred the working of this program and find out that it is due to NULL value assignment to int n2.
I am bit confused how can I achieve above problem using single textbox?
Is there any way to provide the textbox.txt value through user through textbox field only?
Is there any property of textbox which I need to set?
I am very new to .net! Please help!
Thanks in advance for your kind attention!
move n2 = Convert.Int32(textbox1.Text); to your result button's click event
Add button click event:
n1=convert.Int32(textbox1.text);
textbox1.text="";
result button's click event:
n2=convert.Int32(textbox1.text);
result=n1+n2;
textbox1.text=result.tostring();
try something like this:
private int result=0;
addMethod()
{
//here you can use also int.TryParse
if(string.isnullorempty(textbox1.text.trim()))
textbox1.text="0";
result+=convert.toint32(textbox1.text);
textbox1.text=string.empty;
}
resultMethod()
{
textbox1.text=result.tostring();
}
look at the folloing code
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}
You code contains a couple of errors:
You are using Int32 Convert.ToInt32(String) which is bad, because will throw an exception if the user enters something that can't be cast to an Int32, you should use Boolean Int32.TryParse(String, out Int32) instead, and check if the conversion is successful.
You are calling n2 = Convert.ToInt32(textbox1.Text); right after you set textbox1.Text = ""; and this is also bad, because it won't wait for a user input, it will try to convert an empty string to an integer right away, which will yield an exception.
You can't know when the user has finished inserting his number, so you have to rely to something external to the TextBox to let you know you should perform the addition.
Try the following:
Place a TextBox.
Place a Button.
Initialize a "grandTotal" integer variable to zero.
When the user press the button, parse the content of the TextBox in a temporary "submittedValue" integer variable, then sum this temporary variable to your "grandTotal" variable, and display the resulting "grandTotal" variable value.
This way you'll be able to continuously perform the addition operation on the previous total.
Example
The global variable:
protected Int32 GrandTotal = 0;
The Button click event handler:
Int32 currentValue = 0;
if (Int32.TryParse(userValue.Text, out currentValue))
{
GrandTotal += currentValue;
MessageBox.Show(String.Format("The new total is: {0}", GrandTotal));
}
else
{
MessageBox.Show("Invalid value!");
}
I have no idea why you are doing it in this fashion.
Still you can do this as
Declare n1, n2 as int? at the form level
Then in your Add click event do it in this fashion
if (! n1.HasValue)
{
n1 = int.Parse(textBox1.Text);
}
n2 = int.Parse(textBox1.Text);
textBox1.Text = "";
if you are going to do this for lotz of number then use List<int?> myIntList = new List<int?>() and your add event would be
myIntList.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
and the result is int? result = myIntList.Sum();
I have something to do under a button click (add values to listbox) only if a particular string changes from its previous value. How do I manage this? Below is a sample of my code:
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
I can at times have same value for string x from previous value when clicking button6. In such cases I don't want listBox1 to add the item (string x). How to add to listbox only when value of string changes? There's no way to predetermine string x. It gets value when program is running.
Note: adding values to listBox1 every single time and later deleting the duplicates wont work in my program.
Have you considered keeping a copy of the old string value around in a private field, and simply comparing the new value to the old value to see if they match?
For example:
// holds a copy of the previous value for comparison purposes
private string oldString = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
// Get the new string value
string newString = //some varying value I get from other parts of my program
// Compare the old string to the new one
if (oldString != newString)
{
// The string values are different, so update the ListBox
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
// Save the new value back into the temporary variable
oldString = newString;
}
Edit: As the other answers suggest, there are certainly other, more complicated solutions, like encapsulating all access to the string value in a property, or wrapping the string in a custom class. Some of these alternatives have the potential to be "cleaner", more object-oriented approaches. But they're all more complicated than simply saving the previous value in a field. It's up to you to decide whether your specific use case merits the complicated solution, or a simpler one. Think about long-term maintainability, not what's easier for you to implement right now.
string last = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
if(x!=last)
{
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
last = x;
}
}
If this string is super important and gets passed around alot, maybe you should wrap it in a class. The class can hold the string value as a property, but also keep track of when it has changed.
public class StringValue
{
private bool _changed;
public string StrValue{get; set{ _changed = true;}
public bool Changed{get;set;}
}
this is rudimentery of course
I'm not sure I understand completely, but it sounds like you should be using a property to set String x;
string _x = string.Empty;
public string X
{
set
{
if(value != this._x)
{
DoFancyListBoxWork();
this._x = value;
}
}
get
{
return this._x;
}
}
If this is web application, store your last value into session variable. If this is windows application, store it at a class level variable or in singleton class and use this last value for comparison with new value.
On the page load add the current value to viewstate and at the button click check the current value is equal to the value in the view state. If both are equal we can say that the value is not changed.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentValue"] = Your Value;
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
if (NewValue== ViewState["CurrentValue"].ToString())
{
lblmsg.Text = "value is not changed..";
return;
}
else
lblmsg.Text = "value is changed..";
}
You can check the detailed article in this link.
Check Control Value is changed or not
First, I'd like to ask you to check most of the other answers. They are more complete, in that they treat more global issues of tracking the changes of a variable.
Now, I'm assuming, from reading the snippet of code you provided, that you need to track if a string was changed by the user. So, in other words, you probably have a TextBox or other kind of control through which the user can change that value. This is where you should focus your attention: just consume the TextChanged event.
If, however, I'm mistaken and your string comes from any other kind of external source, either use the wrapper class suggested by #Ryan Bennett or, if you are using .Net 4, use a dynamic container, which raises a PropertyChanged event whenever any property is changed.
When I use a numbericupdown object with thousandsseperator set to true it only updates the text to display the commas correctly when it loses focus. Is there a way to force it to refresh each time the value is changed?
You would need to do an event.
As we know, the thounsandseperator is triggered by focus we can simply call it as we type.
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
numericUpDown1.Focus();
//Edit:
numericUpDown1.Select(desiredPosition,0)
}
So as the user type, we give the box the it focus back which is a hack to recall the thousandsseperator formatting.
Note: Problems with hacks are wierd situations which calls for more hacks... e.g: Cursor sets back to the front of the text... you would need another hack to fix it.
Experiment with the other events to find the one that fits your case.
Edit: Btw, if you do want to go even further with this ...
Keep Track of the cursor.
Put back the cursor at the right position when keyup is called.
Setting the cursor position in numericUpDown control
To format the text value in your control you'd need a call to ParseEditText() which is protected but can be accessed from a class which inherits NumericUpDown. The problem is after your call the cursor will move before the first character. In order to control the position of the cursor you need access to the SelectionStart property which NumericUpDown don't expose. NumericUpDown still has a field named upDownEdit of type UpDownEdit. The UpDownEdit class although internal inherits from TextBox and behave much like one. So a solution would be to inherit from NumericUpDown and use reflection to get/set the value of upDownEdit.SelectionStart. Here is something you can work on:
public class NumericUpDownExt : NumericUpDown
{
private static FieldInfo upDownEditField;
private static PropertyInfo selectionStartProperty;
private static PropertyInfo selectionLengthProperty;
static NumericUpDownExt()
{
upDownEditField = (typeof(UpDownBase)).GetField("upDownEdit", BindingFlags.Instance | BindingFlags.NonPublic);
Type upDownEditType = upDownEditField.FieldType;
selectionStartProperty = upDownEditType.GetProperty("SelectionStart");
selectionLengthProperty = upDownEditType.GetProperty("SelectionLength");
}
public NumericUpDownExt() : base()
{
}
public int SelectionStart
{
get
{
return Convert.ToInt32(selectionStartProperty.GetValue(upDownEditField.GetValue(this), null));
}
set
{
if (value >= 0)
{
selectionStartProperty.SetValue(upDownEditField.GetValue(this), value, null);
}
}
}
public int SelectionLength
{
get
{
return Convert.ToInt32(selectionLengthProperty.GetValue(upDownEditField.GetValue(this), null));
}
set
{
selectionLengthProperty.SetValue(upDownEditField.GetValue(this), value, null);
}
}
protected override void OnTextChanged(EventArgs e)
{
int pos = SelectionStart;
string textBefore = this.Text;
ParseEditText();
string textAfter = this.Text;
pos += textAfter.Length - textBefore.Length;
SelectionStart = pos;
base.OnTextChanged(e);
}
}