c# Cannot implicitly convert type 'double' to System.Window.Forms.Textbox - c#

I have this error code "Cannot implicitly convert type 'double' to System.Window.Forms.Textbox" and i'm not sure why i'm getting it. If some one could exlpain it it would be great and give me ideas on how to fix it please. I have looked at other post but still can not work it out.
Thank you for your help
int SumOfSquares(int txtSide1, int txtSide2)
{
txtSide1 *= txtSide1;
txtSide2 *= txtSide2;
return txtSide1 + txtSide2;
}
private void btnCalculate_Click(object sender, EventArgs e)
{
int Side1 = int.Parse(txtSide1.Text);
int Side2 = int.Parse(txtSide2.Text);
int SumLessOne = SumOfSquares(Side1, Side2) - 1;
if (SumOfSquares(Side1, Side2) > 50)
{
txtHypotenuse.Text = "Overflow";
}
else
{
txtHypotenuse.Text = "Safe";
}
txtHypotenuse.Text = Math.Sqrt(SumOfSquares(Side1 , Side2)); // this is the line the error is on
}
}

Add ToString()
txtHypotenuse.Text = Math.Sqrt(SumOfSquares(Side1 , Side2)).ToString();

txtHypotenuse.Text = Convert.ToString(Math.Sqrt(SumOfSquares(Side1 , Side2)));

Related

Winforms Get/Set between classes causing error - Object Reference Error

Having trouble solving this one. Might just be burned out tbh, ive been at this for hours. I am new to Classes in C# and it is kicking the crap out of me trying to pass data between classes. I know there are steps that I am missing, but microsoft docs is not being very helpful with my question so here goes.
Trying to pass values from once class to another. The error code I am getting is CS0120
This is the format of what i am using within the first class
private void btn_Compute_Click(object sender, EventArgs e)
{
decimal dL = Validator(box_Left.Text);
decimal dR = Validator(box_Right.Text);
decimal Answer = 0;
string op = "";
if (rad_Add.Checked == true)
{
MathFirstClass.Left = dL;
MathFirstClass.Right = dR;
op = " + ";
}
}
and the code inside the other class that I am trying to send the data to looks like this
decimal left;
decimal right;
decimal Answer;
public decimal Left
{
get { return left; }
set { left = value; }
}
public decimal Right
{
get { return right; }
set { right = value; }
}
public decimal Add_Operands
{
get
{
Answer = Left + Right;
return Answer;
}
}
Also if anyone wants to fill me in on how to send the answer back to the first class that would also be a great help.
You create an instance of your class.
private void btn_Compute_Click(object sender, EventArgs e)
{
decimal dL = Validator(box_Left.Text);
decimal dR = Validator(box_Right.Text);
decimal Answer = 0;
string op = "";
//****************************************
MathFirstClass mathFirstClass = new MathFirstClass();
if (rad_Add.Checked == true)
{
mathFirstClass.Left = dL;
mathFirstClass.Right = dR;
op = " + ";
}
}

How to solve textbox text changed event..?

private void rateTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(pieceTextBox.Text))
{
}
else if (string.IsNullOrEmpty(rateReturnTextBox.Text))
{
}
else
{
int piece = Convert.ToInt32(pieceTextBox.Text);
int rate = Convert.ToInt32(rateTextBox.Text);
int netTotal = piece * rate;
netTotalBillTextBox.Text = netTotal.ToString();
}
}
//why dose not show the multiplication answer....where is the mistake?
I want this answer in netTotalBillTextBox .
Apparently, in the second condition shouldn't compare rateTextBox?
I assume it will always return string.Empty in rateReturnTextBox.

Pass += or -= as a parameter in c#

I have a method from a button click with the following code in c# (small golf scoring program I'm working on just for fun):
private void btnPlus_Click(object sender, EventArgs e)
{
btnMinus.Enabled = true;
if (f_intHoleNumber != 18) { f_intHoleNumber += 1; }
if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
txtHoleNumber.Text = f_intHoleNumber.ToString();
}
I would like to refactor that and extract another method from it so I don't reuse code but i'm not sure if its possible to pass an operator (+=) as a parameter to a method. Can this be done?
I don't think so. What about passing +1 or -1 to the method and multiplying it with the value to add or to subtract.
For example:
public float calc(float val1, float val2, int op)
{
return val1 + op * val2;
}
You can pass a method that does the adding and subtracting for you. You probably want to go that route.
Pass Method as Parameter using C#
You could pass a Func<int, int> which accepts one int parameter and returns an int.
private void btnPlus_Click(object sender, EventArgs e)
{
HandleHoleChange(currentHole => currentHole + 1);
}
private void HandleHoleChange(Func<int, int> getNextHoleFunc)
{
btnMinus.Enabled = true;
if (f_intHoleNumber != 18) { f_intHoleNumber = getNextHoleFunc(f_intHoldNumber); }
if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
txtHoleNumber.Text = f_intHoleNumber.ToString();
}
the accepted answer allows to pass a 0 which would mess up the calculation. If you want only to allow for addition or subtraction you can use a boolean variable to specify it in the parameterlist:
public float calc(float val1, float val2, bool add)
{
int op = add ? 1 : -1;
return val1 + op * val2;
}

cannot implicity convert string to int [duplicate]

This question already has answers here:
Cannot implicitly convert type 'string' to 'int'
(7 answers)
Closed 8 years ago.
TextBox1.Enabled = false;
finalpricebox.Items.Clear();
namebox.Items.Clear();
int current = 0;
pricebox.Items.Clear();
if (CheckBox1.Checked == true)
{
request.Navigate("http:----------" + TextBox1.Text);
}
else if (CheckBox1.Checked == false)
{
request.Navigate("http://----" + TextBox1.Text);
}
namebox.Focus();
while (!(request.ReadyState == WebBrowserReadyState.Complete))
{
Application.DoEvents();
}
WebClient tClient = new WebClient();
int resultnr = request.Document.GetElementById("searchResults_total").OuterText;
if (resultnr > 30)
{
resultnr = 30;
}
it says that cannot implicity convert string to int. on the line
int resultnr = request.Document.GetElementById("searchResults_total").OuterText;
if (resultnr > 30)
why do i get this error, i really hope someone can help me out
int resultnr = Convert.ToInt32(request.Document.GetElementById("searchResults_total").OuterText);
Recommend to use Int32.TryParse for safe side
int resultnr =0;
if(int.TryParse(request.Document.GetElementById("searchResults_total").OuterText,out resultnr )
{
if (resultnr > 30)
{
resultnr = 30;
}
}

Overloading methods in WPF C#

Hi there I'am quite new to c# and WPF and was wondering if anyone could help me with a problem that I am currently having. I am trying to overload 3 methods in a very simple and basic wpf app (just to see how/if it works) but at run time when I try to check option one or two the application reports and error and closes. However If I check option 3 the application runs as intended. Any one that has any hints tips or solutions would be great. (Here is a code snippet of my basic app).
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void calculate_Click(object sender, RoutedEventArgs e)
{
int val = int.Parse(first.Text);
int val1 = int.Parse(second.Text);
int val2 = int.Parse(third.Text);
if ((bool)oneValue.IsChecked)
showTotal(val);
else if ((bool)twoValues.IsChecked)
showTotal(val, val1);
else if ((bool)threeValues.IsChecked)
showTotal(val, val1, val2);
}
private void showTotal(int val, int val1, int val2)
{
val = int.Parse(first.Text);
val1 = int.Parse(second.Text);
val2 = int.Parse(third.Text);
int total = val + val1 + val2;
result.Text = total.ToString();
}
private void showTotal(int val, int val1)
{
val = int.Parse(first.Text);
val1 = int.Parse(second.Text);
int total = val + val1;
result.Text = total.ToString();
}
private void showTotal(int val)
{
val = int.Parse(first.Text);
result.Text = val.ToString();
}
private void quit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Your overloads look correct to me. You probably don't have anything in your second or thrid text box if the second or third checkbox is not checked (it's hard to tell without more details). So the first thing you are doing is parsing all three text boxes, but if it's empty then you will get an exception. You can use TryParse which attempts to parse the string, but if it can not just returns false and you can gracefully handle it.
What I would do is something like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void calculate_Click(object sender, RoutedEventArgs e)
{
int val, val1, val2;
if (!int.TryParse(first.Text, out val))
{
val=0; // Invalid or blank input get's a zero (or you could show an error message)
}
if (!int.TryParse(second.Text, out val1))
{
val1=0; // Invalid or blank input get's a zero (or you could show an error message)
}
if (!int.TryParse(third.Text, out val2))
{
val2=0; // Invalid or blank input get's a zero (or you could show an error message)
}
if ((bool)oneValue.IsChecked)
showTotal(val);
else if ((bool)twoValues.IsChecked)
showTotal(val, val1);
else if ((bool)threeValues.IsChecked)
showTotal(val, val1, val2);
}
private void showTotal(int val, int val1, int val2)
{
int total = val + val1 + val2;
result.Text = total.ToString();
}
private void showTotal(int val, int val1)
{
int total = val + val1;
result.Text = total.ToString();
}
private void showTotal(int val)
{
result.Text = val.ToString();
}
private void quit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
I see two things wrong with this code. The first is that I'm going to guess that you're having input validation in that the text can't be parsed into an integer. As a best practice, use int.TryParse, i.e.
int val;
if (!int.TryParse(first.Text, out val))
{
// Handle error
}
The second issue is that you're basically overwriting any parameters you're passing in. Why not just either have different methods for the # of inputs, or take a single parameter that indicates how many inputs you should use.
In fact, I'm not sure that overloading here is the correct approach. Why not use params:
private void showTotal(params string[] inputs)
{
int total = 0;
foreach (string input in inputs)
{
int val;
if (int.TryParse(input, out val))
total += total;
}
result.Text = total.ToString();
}
You can call it like
if ((bool)oneValue.IsChecked)
showTotal(first.Text);
else if ((bool)twoValues.IsChecked)
showTotal(first.Text, second.Text);
else if ((bool)threeValues.IsChecked)
showTotal(first.Text, second.Text, third.Text);
1) You are trying to parse your values twice
2) here Your bool cast is redundant because IsChecked already bool
if ((bool)oneValue.IsChecked)
3) Instead of parse, use TryParse it won't throw exception
int val, val1, val2;
if (oneValue.IsChecked)
{
if (int.TryParse(first.Text, val))
{
showTotal(val);
}
}
else if (twoValues.IsChecked)
{
if (int.TryParse(second.Text, val1))
{
showTotal(val, val1);
}
}
else if (threeValues.IsChecked)
{
if (int.TryParse(third.Text, val2)
{
showTotal(val, val1, val2);
}
}
4) Also you can use params keyword instead of method overloading.I guess it is more suitable in your case.With params keyword you can do your job with one method like this:
private void showTotal(params int[] numbers)
{
if(numbers != null)
{
int sum = numbers.Sum();
result.Text = sum.ToString();
}
}
Are you sure that the value of first.Text, second.Text, and third.Text are integer values? Calling int.Parse() on a non-integer value will throw an error. You might want to look into using int.TryParse() instead:
private void showTotal(int val)
{
bool gotResult = int.TryParse(first.Text, out val);
if(gotResult)
result.Text = val.ToString();
}
Furthermore, I'm pretty sure you application is failing on the "one" and "two" scenarios because this code:
private void calculate_Click(object sender, RoutedEventArgs e)
{
int val = int.Parse(first.Text);
int val1 = int.Parse(second.Text);
int val2 = int.Parse(third.Text);
Will fail unless first, second, and third all contain values. If second or third contains null or an empty string, you will get an error from int.Parse.

Categories

Resources