ComboBox 和 ListBox 不显示文本文件的内容



我有一项任务要为冰淇淋店创建订单,为了将浇头和口味放入列表和组合框,我需要从文本文件中读取。我遵循了说明和非常糟糕的视频教程,我在bin/debug文件夹中有我的文本文件,文件上有各自的风格和标题。它运行良好,只是下拉列表是空白的,列表框也是空白的。这是C#,我正在使用一个windows窗体应用程序。这是我的代码

namespace Lab5_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
saveButton.Text = "&Save";
exitButton.Text = "&Exit";
}
private void Form1_Load(object sender, EventArgs e)
{
PopulateBoxes();
flavorsComboBox.SelectedItem = "Vanilla";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void saveButton_Click(object sender, EventArgs e)
{
try
{
// writes order information to output file
StreamWriter outputFile;
outputFile = File.AppendText("Orders.txt");
outputFile.WriteLine(DateTime.Now.ToString("mm/dd/yyyy"));
if (sugarConeRadioButton.Checked)
{
outputFile.WriteLine("Sugar Cone");
}
else
{
outputFile.WriteLine("Waffle Cone");
}
outputFile.WriteLine(flavorsComboBox.SelectedItem.ToString());
for (int count = 0; count < toppingsListBox.Items.Count; count++)
{
if (toppingsListBox.GetSelected(count))
{
outputFile.WriteLine(toppingsListBox.Items[count]);
}
}
outputFile.WriteLine();
outputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sugarConeRadioButton.Checked = true;
flavorsComboBox.SelectedItem = "Vanilla";
toppingsListBox.ClearSelected();
sugarConeRadioButton.Focus();
}
private void PopulateBoxes()
{
try
{
StreamReader inputFile;
inputFile = File.OpenText("Flavors.txt");
while (inputFile.EndOfStream)
{
flavorsComboBox.Items.Add(inputFile.ReadLine());
}
inputFile.Close();
inputFile = File.OpenText("Toppings.txt");
while (inputFile.EndOfStream)
{
toppingsListBox.Items.Add(inputFile.ReadLine());
}
inputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
}
}

如果您希望逐行显示整个文件内容,如果您使用System.IO.File.ReadAllLines帮助程序,则文件IO的使用寿命会更轻松

例如

private void PopulateBoxes()
{
try
{
flavorsComboBox.DataSource = File.ReadAllLines("Flavors.txt").ToList();
toppingsListBox.DataSource = File.ReadAllLines("Toppings.txt").ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void PopulateBoxes()
{
try
{
flavorsComboBox.Items.AddRange(File.ReadAllLines("Flavors.txt"));
toppingsListBox.Items.AddRange(File.ReadAllLines("Toppings.txt"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

最新更新