Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# datagridview正在抱怨';索引超出范围。必须为非负数且小于集合的大小;_C#_Datagridview - Fatal编程技术网

C# datagridview正在抱怨';索引超出范围。必须为非负数且小于集合的大小;

C# datagridview正在抱怨';索引超出范围。必须为非负数且小于集合的大小;,c#,datagridview,C#,Datagridview,上面是我的代码。如上所述,它在线路上崩溃。我无法想象它为什么会崩溃。非常感谢您的帮助。您的热线: private void importFile() { TextFieldParser parser = new TextFieldParser(@"E:\\test.csv"); parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(",");

上面是我的代码。如上所述,它在线路上崩溃。我无法想象它为什么会崩溃。非常感谢您的帮助。

您的热线:

    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();
    }
将在第一次执行时失败,因为此时dataGridView1中没有行,因此index=0超出范围

请尝试以下方法:

DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
您可以在此处阅读更多内容:


接近您的代码

DataGridViewRow row = new DataGridViewRow();    

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

您的
Datagridview1
有行吗?@SonerGönül看到代码中的三行注释。@Cocoa Dev循环运行了多少次并且崩溃了?或者仅在第一次尝试中?dataGridView1.Rows.Count的值是多少?(在进入循环之前)循环应在第一次ITEATION时失败,因为访问dataGridView1时没有行。行[0]。这不是构造行的正确方法。这样更有效吗?我的文件有45K个条目,用户界面冻结。我必须将负载放到后台线程中,因为迭代开销最小化了。但不管怎样,如果你处理的是大文件,后台线程还是不错的。我尝试了与你建议的相同的方法,但得到了相同的异常
    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);
        }
    }