質問

I have:

    private void btnAddScore_Click(object sender, EventArgs e)
    {
        if (IsInt32())     
        {
            txtScores.Text += txtScore.Text + " ";
            txtScore.Text = "";
        }
    }

and:

    private void button2_Click(object sender, EventArgs e)
    {
        if (IsValidData())
        {
            List<string> result = txtScores.Text.Split(' ').ToList();
            student = new Student(txtName.Text, result.Select(int.Parse).ToList());
            this.Close();
        }

    }

I'm trying to use my btnAddScore to build a string of scores from my txtScore to my txtScores. This I believe I'm doing correctly. Then I'm converting that string into a list by Parsing each element with " ". I then further convert the List < string > into a List < int >. No compiler errors but a runtime error of "FormatException was undandled" and points to (int.Parse). I've read that int.Parse will cause this if used on an empty string, but I don't see how that's the case if it is.

役に立ちましたか?

解決

Because you are appending a white space the "Split" method returns an empty element at the end wich you are not expecting, add na option "SplitOptions.RemoveEmptyEntries" (from head, check if it is the correct name) and your code will work.

他のヒント

You could use TryParse like this,

student = new Student(txtName.Text, result.Select(s =>
    {
        int res = 0;
        return int.TryParse(s, out res) ? res : 0;
    }).ToList());

This code will avoid the exceptions you are getting and if it can not parse any value it will set it to 0

The issue is that one of your string is not valid int after splitting by space (' '). I would suggest to consider only those scores which are valid number.

Let's consider below scores separated by space

111 123 12x 212 1454

here 12x is not valid so you should reject this number. and get only four valid numbers as shown in below code sample :

var scores = "111 123 12x 212 1454";
var regex = new Regex("^[0-9]*$");
var studentScore = scores.Split(' ').Where(a => regex.IsMatch(a)).ToList();

This error is easily debugged by setting a break point in Visual Studio on the following line:

student = new Student(txtName.Text, result.Select(int.Parse).ToList())

...and then inspecting result list manually. One of the strings definitely is not a parseable int.

In short: You have a good error message and should be able to find this error quickly by using standard debugging techniques.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top