1

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);
    }
Roman
  • 1,267
  • 2
  • 13
  • 20

3 Answers3

3

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.

Schuere
  • 1,579
  • 19
  • 33
1

Try using TryParse Method :

 int number = Int32.Parse(arg); /*Instead of this line in your code use below.*/

A possible duplicate thread

Community
  • 1
  • 1
Kaushal B
  • 46
  • 7
  • Few other duplicate [threads](http://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) or also check this [MSDN](https://msdn.microsoft.com/en-IN/library/bb397679.aspx) – Kaushal B Nov 10 '15 at 06:56
0

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

Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51