简体   繁体   中英

FormatException was unhandled (int.Parse)

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.

因为要添加空格,所以“ Split”方法将在不期望的末尾返回一个空元素,因此请添加一个选项“ SplitOptions.RemoveEmptyEntries”(从头开始,检查其名称是否正确),然后代码即可正常工作。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM