首页 > 解决方案 > 字符串格式错误c#

问题描述

我试图弄清楚为什么当我运行我的程序并按下提交按钮时我收到一个错误,说我的列表格式错误。该程序的一些背景知识:这是针对我的可视化编程课程的。该程序适用于银行帐户。我试图评论每个部分的内容,以使其更易于阅读

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //Tab 1 Create and close account
    private void Submitbtn_Click(object sender, EventArgs e)
    {
        double x;

        if (OpenRdo.Checked == true && Nametxtbx.TextLength > 0)
        {
            double.TryParse(Nametxtbx.Text, out x);

            // after clicking the button there is
            // no number; it says system.random
            Random acct = new Random();                
            int AccountNumber = acct.Next(5, 1000);
            outputlbl.Text = acct.ToString();
        }

        // list for accounts 
        // This is where it says I have the error
        // that my list is in the wrong format
        var accounts = new List<Account>
        {
            new  Account(Nametxtbx.Text, double.Parse(outputlbl.Text), 0)
        };

        // Write these records to a file
        WriteFile(accounts);

        // message box when you create account
        if (ValidateChildren(ValidationConstraints.Enabled))
        {
            MessageBox.Show("Account Created", "Message", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    //writing to the file
    static void WriteFile(List<Account> accts)
    {
        StreamWriter outputFile = File.CreateText("accounts.txt");
        string record;

        foreach (var acct in accts)
        {
            record = $"{acct.Name},{acct.Balance}";
            Console.WriteLine($"Writing record: {record}");
            outputFile.WriteLine(record);
        }

        outputFile.Close();
    }
}

标签: c#

解决方案


据我所知(这是相当多的代码),问题在于这些行:

Random acct = new Random();                
int AccountNumber = acct.Next(5, 1000);
outputlbl.Text = acct.ToString();

您将标签设置为“System.Random”(因为您在错误的事情上调用了 ToString())。以后不能明智地将其转换为整数。

理想情况下,您甚至不应该从 UI 中检索数据。如果后面的代码中有一个整数,请将其保留在那里。用它。但是由于事件之间的分离可能并不总是可能的。


推荐阅读