0

所以我有这门课

namespace WindowsFormsApplication2
{ 
    public class Records
    {
        public string name, surname;

        public int num;
    }
}

我想创建一个此类的数组,尝试了一切,但它仍然不起作用,我开始认为这是一个错误,我使用的是 Visual Studio 2012,这是我的代码。任何帮助将不胜感激。

(表单上有一个记录数据网格,我从文本框中读取,信息用制表符分隔)

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Records[] userRecs = new Records[20];

        public int count = 0;


        private void Form1_Load(object sender, EventArgs e)
        {
            getText();
        }

        public void getText() 
        {
            FileStream fs = new FileStream("D:\\filestr.txt",FileMode.Open);

            StreamReader sr = new StreamReader(fs);

            for (string readed = sr.ReadLine(); readed != null; readed = sr.ReadLine())
            {
                string[] tempStr = readed.Split('\t');

                userRecs[count].num = Convert.ToInt32(tempStr[0]);

                userRecs[count].name = tempStr[1];

                userRecs[count].surname = tempStr[2];

                count++;
            }

            for (int i = 0; i < count; i++)
            {
                dataGridView1.Rows.Add(userRecs[count].num, userRecs[count].name, userRecs[count].surname);
            }

            sr.Close();
            fs.Close();
        }
    }
}
4

2 回答 2

8

这会为数组分配内存,但不会创建 Record 实例:

Records[] userRecs = new Records[20];

现在,当您遍历文件行时,您需要实例化您的类:

userRecs[count] = new Records();
userRecs[count].num = ...
...
于 2012-11-16T21:27:26.863 回答
2
 dataGridView1.Rows.Add(userRecs[count].num, userRecs[count].name, userRecs[count].surname);

可能应该是

dataGridView1.Rows.Add(userRecs[i].num, userRecs[i].name, userRecs[i].surname);
于 2012-11-16T21:25:35.683 回答