开发者

Textbox Null Question

So basically I'm trying to make a Windows Form Application to calculate the average of 4 test grades. However, in some classes, I may only have 3 tests. Without a value in all four test textboxes the program will not calculate the average. I'm trying to figure out a way to code if the fourth text box has nothing in it, just ignore it and calculate the other 3. My code is below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GradeCalc
{
    public partial class Grades : Form
    {
        public Grades()
        {
            InitializeComponent();
        }

        private void Submit_Click(object sender, EventArgs e)
        {
            double test1;
            double test2;
            double test3;
            double test4;
            double average4;
            double average3;

            //Here, I'm trying to achieve:
            //if (t4 is empty)
            //{find the average of the first 3 textboxes}

            if (t4.Text == null)
            {
                test1 = double.Parse(t1.Text);
                test2 = double.Parse(t2.Text);
                test3 = double.Parse(t3.Text);
                average3 = ((test1 + test2 + test3) / 3);
                tavg.Text = average3.ToString("00.00");
            }
                //Here, I'm trying to achieve:
                //if (t4 is not e开发者_StackOverflow中文版mpty)
                //{ calculate the average of all 4 textboxes}

            else
                if (t4.Text != null)
                {
                    test1 = double.Parse(t1.Text);
                    test2 = double.Parse(t2.Text);
                    test3 = double.Parse(t3.Text);
                    test4 = double.Parse(t4.Text);
                    average4 = ((test1 + test2 + test3 + test4) / 4);
                    tavg.Text = average4.ToString("00.00");
                }
        }
    }
}

I do not have a lot of experience with C#, so any help would be appreciated thanks.


Try String.IsNullOrEmpty(t4.Text)


try this:

List<double> MyValues = new List<double>;

double T;

if ( double.TryParse ( t1.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t2.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t3.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t4.Text, out T) )
     MyValues.Add (T);

if ( MyValues.Count > 0 )
     tavg.Text = MyValues.Average ().ToString ("00.00");

the code above is robust... if any of the texts (t1 - t4) is not a valid number it is skipped... the average is calculated for the correct values (whether 1, 2, 3 or 4) only... and it takes care of the case that no valid value has been entered...

You could easily modify it to require that at least 3 valid numbers are entered bei changing the last if to if ( MyValues.Count > 3 ) for example.


The fourth textbox's content is probably not not null but just an empty string. You could use String.IsNullOrEmpty() rather than the comparison with null to cover all angles. But what if someone puts in a space or something. You might want to trim out whitespace too.

A total alternative would be to use the TryParse method rather than Parse - and then use the returned success boolean to decide how many results you have. TryParse works like this:

if (Double.TryParse(t4.Text, out test4))
{
   // this works
}
else
{
   // this did not
}


You can improve your code by decoupling the various tasks you want to undertake. Initially you want to parse the numbers in the text boxes. You can do that using a function:

IEnumerable<Double> ParseValues(IEnumerable<TextBox> textBoxes) {
  foreach (var textBox in textBoxes) {
    Double value;
    if (Double.TryParse(textBox.Text, out value))
      yield return value;
  }
}

This function will take an input sequence of TextBox objects and produce an output sequence of Doublevalues skipping all text boxes with invalid values.

You can then use this function to computer the average:

var values = ParseValues(new[] { t1, t2, t3, t4 });
if (values.Any()) {
  var average = values.Average();
  tavg.Text = average.ToString("00.00");
}

This code will compute the average if any or all of the text boxes contain valid values.


See the other answers that talk about TryParse or the contents of the text-box. This is just an annotation to those.

FWIW, I have helper functions to make life easier, for instance:

double? AsDouble (string str) {
  double value;
  if (double.TryParse(str, out value))
    return value;
  } else {
    return null;
  }
}

Then it's as easy as:

double val = AsDouble(txt.Text) ?? 0;

(Where 0 is the number to default to.)

Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜