c# - 字符串格式错误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();
}
}
解决方案
据我所知(这是相当多的代码),问题在于这些行:
Random acct = new Random();
int AccountNumber = acct.Next(5, 1000);
outputlbl.Text = acct.ToString();
您将标签设置为“System.Random”(因为您在错误的事情上调用了 ToString())。以后不能明智地将其转换为整数。
理想情况下,您甚至不应该从 UI 中检索数据。如果后面的代码中有一个整数,请将其保留在那里。用它。但是由于事件之间的分离可能并不总是可能的。
推荐阅读
- bash - bash 脚本采购位于另一个目录中的 bash 脚本
- c++ - ~ 和 - 之间的区别
- c++ - 如何使用头文件中的结构,该结构还具有其他一些功能?
- bash - 处理交换文件 BASH 的数据
- python - 如何将我的 ui 表单连接到 mysql 并使用 ui 表单插入数据?
- r - 当呼叫不是来自 R 中的“aov()”或“lm()”时停止?
- sql - 如何跨数据库表强制执行业务规则?
- javascript - 在 Angular 中显示从控制台到 HTML 的简单 JSON 数据
- python - pip install virtualenvwrapper-powershell 不工作
- android - 从 OnAttach 将监听器接口注入父片段