public bool TextToDgv(string path) // 这个函数那里出错了?
{
System.Data.DataTable table1 = new System.Data.DataTable();//定义数据存放的表
StreamReader reader = new StreamReader(path,Encoding.Default);
string[] cols;
string[] row;
string tempdata;
tempdata =(string) reader.ReadLine();
tempdata = tempdata.Trim();
if (tempdata == "")
{
MessageBox.Show("没东西啊");
return false;
}
cols = tempdata.Split('\x20');
for (int i = 0; i < cols.Length; i++)//添加列头
{
table1.Columns.Add(cols[i], typeof(string));
}
try
{
while (reader.Peek() != -1) //添加行
{
System.Data.DataRow datarw = table1.NewRow();
tempdata = reader.ReadLine();
tempdata = tempdata.Trim();
row = tempdata.Split('\x20');
for (int i = 0; i < table1.Columns.Count; i++)
{
datarw[i] = row[i];
}
table1.Rows.Add(datarw);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
dataGridView.DataSource = table1;//将表与dataGridView绑定
return true;
}
错误提示是
索引超出数组下标,未将对象引用设置到实例。小弟初学c#,各位大大帮下
{
System.Data.DataTable table1 = new System.Data.DataTable();//定义数据存放的表
StreamReader reader = new StreamReader(path,Encoding.Default);
string[] cols;
string[] row;
string tempdata;
tempdata =(string) reader.ReadLine();
tempdata = tempdata.Trim();
if (tempdata == "")
{
MessageBox.Show("没东西啊");
return false;
}
cols = tempdata.Split('\x20');
for (int i = 0; i < cols.Length; i++)//添加列头
{
table1.Columns.Add(cols[i], typeof(string));
}
try
{
while (reader.Peek() != -1) //添加行
{
System.Data.DataRow datarw = table1.NewRow();
tempdata = reader.ReadLine();
tempdata = tempdata.Trim();
row = tempdata.Split('\x20');
for (int i = 0; i < table1.Columns.Count; i++)
{
datarw[i] = row[i];
}
table1.Rows.Add(datarw);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
dataGridView.DataSource = table1;//将表与dataGridView绑定
return true;
}
错误提示是
索引超出数组下标,未将对象引用设置到实例。小弟初学c#,各位大大帮下
{
table1.Columns.Add(cols[i], typeof(string));
}
改为
for (int i = 0; i < cols.Length - 1; i++)//添加列头
{
table1.Columns.Add(cols[i], typeof(string));
} 数组下标是从0开始的! length是个数
for (int i = 0; i < table1.Columns.Count; i++)当你文本文件中的第一行数据的列大小比其它几行数据的列的更大时, 那么就会造成此种异常。
楼主把各行文本的列改成同样大小, 就行了。