0
    private void importFile()
    {
        TextFieldParser parser = new TextFieldParser(@"E:\\test.csv");
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        dataGridView1.Columns[0].Name = "URL";
        dataGridView1.Columns[1].Name = "Valid";

        while (!parser.EndOfData)
        {
            //Processing row
            string[] fields = parser.ReadFields();
            foreach (string field in fields)
            {
                //TODO: Process field
                // Crashes on line below with message
                // Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
                DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();                    


                row.Cells[0].Value = field;
                row.Cells[1].Value = "";
                dataGridView1.Rows.Add(row);
            }
        }
        parser.Close();
    }

以上是我的代码。如上所述,它在线上崩溃。我无法想象它为什么会崩溃。任何帮助将不胜感激。

4

2 回答 2

1

您的线路:

DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();

第一次执行会失败,因为此时dataGridView1中没有行,所以index = 0超出范围。

试试这个:

DataGridViewRow row = new DataGridViewRow();    

你可以在这里阅读更多:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.aspx

于 2013-04-22T13:06:36.983 回答
1

接近你的代码

    private void loadBtn_Click(object sender, EventArgs e)
    {
        string buffer = "1,2,3\r\n4,5,6\r\n7,8,9";
        TextFieldParser parser = new TextFieldParser(new MemoryStream(UTF8Encoding.Default.GetBytes(buffer)));
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        dataGridView1.Rows.Clear();

        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            dataGridView1.Rows.Add(fields);
        }
    }

我的 dagaGridView1 有 3 列。我使用 MemoryStream 而不是文件解析。

于 2013-04-22T13:22:51.373 回答