C#listbox数组有问题

时间:2015-05-05 17:34:25

标签: c# arrays debugging listbox freeze

全部。我正在创建一个程序,将一个团队列表作为字符串数组,并将其与包含所有世界系列赛获胜者列表的.txt文件进行比较,并确定团队赢得世界系列赛的次数在列表框中选择。

我的代码丢失了0个错误,第一次运行程序并选择了一个团队并点击了按钮,显示了显示团队名称的消息框以及他们赢了多少次。在那之后,每当我再次选择一个团队并单击按钮时,没有任何反应。它冻结了。我必须停止调试。什么可能会出错?有什么想法和建议吗?

namespace WorldSeriesWinners
{
    public partial class Form1 : Form
   {
        string[] inputTeams = 
        { 
          "Boston Americans", "New York Giants", "Chicago White Sox","Chicago Cubs",
          "Pittsburgh Pirates", "Philadelphia Athletics","Boston Red Sox", "Boston Braves",
          "Cincinatti Reds", "Cleveland Indians","Brooklyn Dodgers",
          "New York Yankees", "Washington Senators", 
          "St. Louis Cardinals","Detroit Tigers", "Milwaukee Braves",
          "Los Angeles Dodgers", "New York Mets", "Baltimore Orioles",
          "Oakland Athletics", "Philadelphia Phillies", "Kansas City Royals", "Minnesota Twins", "Toronto Blue Jays", 
          "Atlanta Braves", "Florida Marlins", "Arizona Diamondbacks", "Anaheim Angels", "San Francisco Giants"
        };

    string[] worldseriesWinners = new string[104];

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.AddRange(inputTeams);
    }



    private void button2_Click(object sender, EventArgs e)
    {
        StreamReader champFile = File.OpenText("WorldSeriesWinners.txt");
        List<string> inputTeams = new List<string>();
        string selectedTeam;

        while (!champFile.EndOfStream)
        {
            inputTeams.Add(champFile.ReadLine());
        }
        while (listBox1.SelectedIndex != 0)
        {
            selectedTeam = listBox1.SelectedItem.ToString();
        }
        selectedTeam = listBox1.SelectedItem.ToString();
        var count = File.ReadLines("WorldSeriesWinners.txt").Count(x => x.Contains(selectedTeam));

        if (count > 0)
        {
            MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + " times! ");
        }
        else
        {
            MessageBox.Show("The " + selectedTeam + "has never won the World Series.");
        }
    }
}

3 个答案:

答案 0 :(得分:2)

除非您总是选择列表中的第一项作为执行此操作的代码,否则您的代码永远无法运行

while (listBox1.SelectedIndex != 0)
{
    selectedTeam = listBox1.SelectedItem.ToString();
}

将永远保持运行,因为如果您在第一个条目之外选择列表框中的任何其他项目,则listBox1.SelectedIndex将永远不会为0并且它将永远循环。没有理由使用while循环来读取所选项目。

答案 1 :(得分:0)

完成后需要关闭流

private void button2_Click(object sender, EventArgs e)
{
    StreamReader champFile = File.OpenText("WorldSeriesWinners.txt");

 ...
     champFile.Close();
} 

最佳做法是使用using声明

private void button2_Click(object sender, EventArgs e)
{
    using(StreamReader champFile = File.OpenText("WorldSeriesWinners.txt"))
    {

 ...
     }
} 

您可以将File.OpenText包装在try语句中进行测试。并打破了捕获。

答案 2 :(得分:0)

尝试这样做

using(StreamReader champFile = File.OpenText("WorldSeriesWinners.txt")){
...
}