字符串分割出现索引超出了数组界限错误

.Net技术 码拜 8年前 (2016-05-25) 1214次浏览
 private void buttonLoad_Click(object sender, EventArgs e)
{
OnLoadTextFile();
}
void OnLoadTextFile()
{
OpenFileDialog f1 = new OpenFileDialog();
f1.Title = “文件加载”;
f1.Filter = “文本文档(*.txt)|*.txt”;
if (f1.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows.Clear();
//StreamReader sr = new StreamReader(f1.FileName, Encoding.GetEncoding(“GB2312”));
StreamReader sr = new StreamReader(f1.FileName, Encoding.GetEncoding(“gb2312”));
while (!sr.EndOfStream)//当前的流位置能否在流的末尾
{
string text = sr.ReadLine();
string[] item = text.Split(“,”);
int index = dataGridView1.Rows.Add();

dataGridView1[0, index].Value = item[0].Trim();
dataGridView1[1, index].Value = item[1].Trim();
dataGridView1[2, index].Value = item[2].Trim();
dataGridView1[3, index].Value = item[3].Trim();
dataGridView1[4, index].Value = item[4].Trim();//索引超出了数组界限错误
}
sr.Close();
}
}
void OnLoadXmlFile()
{

}
本人小白,加载某个txt文本一直出现索引超出了数组界限错误,这是个BUG,还有中文乱码问题,求指导决办法,谢谢

解决方案

20

引用:

11111,,,,
,二等分,,,
,,144455445654,,
,,,55252,
,,,,Peter
测试这个就出bug

单步调试。
另外,不能保证不越界,就应该加index<Length。

40

乱码的话统一一下编码格式,gb2312  或UTF-8

20

判断一下
if(item .Length>5)
{
// 执行赋值语句
}、
另外这个datagridview 尽量不要这样赋值,
datagridview.DataSource  可以是 DataTable  List<T> DataSet  ……….好多形式的数据
你这样对某行某列赋值很容易出错,一点都不方便

40


dataGridView1[0, index].Value = item[0].Trim();
dataGridView1[1, index].Value = item[1].Trim();
dataGridView1[2, index].Value = item[2].Trim();
dataGridView1[3, index].Value = item[3].Trim();
dataGridView1[4, index].Value = item[4].Trim();//索引超出了数组界限错误
改为

for(int i = 0; i < Math.Min(dataGridView1.ColumnCount, item.Length); i++)
{
    dataGridView1[i, index].Value = item[i].Trim();
}

就可保证不会越界
至于乱码,你最好截个图上来看看


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明字符串分割出现索引超出了数组界限错误
喜欢 (0)
[1034331897@qq.com]
分享 (0)