简体   繁体   English

C#索引不在上下文中

[英]C# index not in context

I am can't figure out how to put the index [i] in the context when I try to write in to the listbox1. 当我尝试写入listbox1时,我无法弄清楚如何将索引[i]放在上下文中。 The code I got so far is: 我到目前为止的代码是:

    private void button1_Click(object sender, EventArgs e)
    {            
        StreamWriter Info = File.AppendText("Contacts.txt");

        for (int i = 0; i < listBox1.Items.Count; i++);
            Info.WriteLine(listBox1.Items[i]);
        Info.Close();
    }

I am trying to make a Windows Form application that accepts names and email addresses and places them in a list box. 我正在尝试创建一个接受名称和电子邮件地址的Windows窗体应用程序,并将它们放在一个列表框中。 Can anyone help me out on what I am missing here? 任何人都可以帮助我解决我在这里失踪的问题吗?

The semicolon in this line for (int i = 0; i < listBox1.Items.Count; i++); 这行中的分号for (int i = 0; i < listBox1.Items.Count; i++); may cause an error. 可能会导致错误。 Delete it and then try again. 删除它,然后再试一次。

I don't know what you are trying to do. 我不知道你要做什么。 I am providing you the possible solutions here as i understood your problem. 我在这里为您提供可能的解决方案,因为我理解您的问题。

  1. If you need to write a file with listbox1 contents, same code with correction by Misa Lazovic: 如果你需要写一个包含listbox1内容的文件,同样的代码由Misa Lazovic修正:

     private void button1_Click(object sender, EventArgs e) { StreamWriter Info = File.AppendText("Contacts.txt"); for (int i = 0; i < listBox1.Items.Count; i++) Info.WriteLine(listBox1.Items[i]); Info.Close(); } 
  2. If you need to read the contents from file and place them to your listbox1 : 如果您需要从文件中读取内容并将它们listbox1

     private void button1_Click(object sender, EventArgs e) { foreach (string s in System.IO.File.ReadAllLines("Contacts.txt")) listBox1.Items.Add(s); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM