我试图找出为什么当我运行我的程序并按下提交按钮时,我得到一个错误,说我的列表格式错误。关于这个程序的一些背景知识:它是为我的可视化编程课程准备的。这个程序是为银行账户准备的。我试着评论每一节是什么,以使它更容易阅读
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();
}
}
发布于 2018-10-23 03:36:34
据我所知(这是相当多的代码),问题是以下几行:
Random acct = new Random();
int AccountNumber = acct.Next(5, 1000);
outputlbl.Text = acct.ToString();
您将标签设置为"System.Random“(因为您在错误的地方调用了ToString() )。这不能在以后合理地转换为整数。
理想情况下,您甚至不应该从UI检索数据。如果你在后面的代码中有一个整数,就把它放在那里。使用它。但随着事件之间的分离,这可能并不总是可能的。
发布于 2018-10-23 03:18:31
我建议,如果你不知道文本框中的内容,不要只解析文本。宁可做这样的事情
if(double.TryParse (outputlbl.Text, out double outputNumber))
{
new Account(Nametxtbx.Text, outputNumber, 0);
}
另外,请看一下formatprovider
https://stackoverflow.com/questions/52936219
复制相似问题