datagridview正在抱怨'索引超出范围.必须非负且小于集合的大小.'
本文关键字:小于 集合 索引 范围 datagridview | 更新日期: 2023-09-27 18:10:23
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();
}
上面是我的代码。如上所述,它在行路上崩溃。我无法想象它为什么会崩溃。如有任何帮助,不胜感激。
你的台词:
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贴近你的代码
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代替文件解析