【发布时间】:2019-09-15 01:34:36
【问题描述】:
我正在尝试为一个项目创建库存系统。我得到了一些类的基本代码,因此得到了列表和对象。
当我尝试使用 WinForms 将文件中的所有这些值返回到 RichTextBox 时,出现编译错误(特别是对于隐式转换)。
我只是想知道除了通常的textbox.txt = "some numbers" 之外,是否还有其他脚本可以在 WinForms 中显示整数。
private void button5_Click(object sender, EventArgs e)
{
List<Bike> Bikes = new List<Bike>();
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] lines = File.ReadAllLines(ofd.FileName);
int invCounter = 0;
int invLength = lines.Length / 8;
for (int i = 0; i < invLength; i++) //for each bike
{
string make = lines[i + invCounter++]; //store the make
string type = lines[i + invCounter++]; //store the type
string model = lines[i + invCounter++]; //store the model
int year = int.Parse(lines[i + invCounter++]); //store the year
string wheelSize = lines[i + invCounter++]; //store the wheel size
string frameType = lines[i + invCounter++]; //store the frame type
//store the security code
int securityCode = int.Parse(lines[i + invCounter++]);
//create a new bike object with the details stored above
Bike bk = new Bike(make, type, model, year, wheelSize, frameType,
securityCode);
Bikes.Add(bk); //add the bike to Bikes list
foreach (Bike bike in Bikes)
{
richTextBox1.Text = bk.Type;
richTextBox1.Text = bk.SecurityCode; // Error here
richTextBox1.Text = bk.Make;
richTextBox1.Text = bk.Model;
richTextBox1.Text = bk.Year; // Error here
richTextBox1.Text = bk.WheelSize;
richTextBox1.Text = bk.Forks;
}
}
}
}
【问题讨论】:
-
问题是
Text属性是string类型,而您尝试存储在Text中的一些Bike属性不是string类型。您需要研究转换和转换数据类型。微软有一篇关于这个here的文章。 -
您的
foreach循环作为一个整体看起来不正确...您真的想在每次向该列表添加新的Bike时循环整个Bikes列表吗? -
@Jaxix - 它可能看起来有效,但如果你追踪它(如果有帮助的话,可能在纸上),它看起来好像做了很多不必要的循环。仅仅因为它编译并不意味着它是正确的。它可能是正确的,但它肯定看起来不正确。
-
@BrootsWaymb 我承认这可能不是最有利的方式,但我对这门语言还是很陌生,我只是接受了我提供的代码并使用它,但我肯定会调查它!