问题
I have a tab delimited file that I want to load in a DataGridView (DGV); for that, I'm using the following code:
DataTable dt = new DataTable();
using (FileStream stream = File.OpenRead("logs.txt"))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = reader.ReadLine();
while (line != null)
{
string[] items = line.Split('\t');
line = reader.ReadLine();
if (dt.Columns.Count == 0)
{
for (int i = 0; i < items.Length; i++)
{
dt.Columns.Add("Column " + i);
}
}
dt.Rows.Add(items);
}
dataGridView1.DataSource = dt;
}
}
The problem is the amount of columns per line is not always the same and that is producing the error "Input array is longer than the columns in this table".
Text example:
x xx xxx xxxx xxxxx
x xx xxx xxxx xxxxx xxxxxx xxxxxxx
x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx
Given the problem, how can I make to pass all the text file to the DGV?
回答1:
First of all, you should try to understand the exception by reading about it and figuring out on what situation this exception is thrown.
Then debug the code the understand why this exception is thrown from your code and try to understand how this can be fixed.
Anyways, coming back to your code.
You are adding new columns to the table only when dt.Columns.Count
is zero. So the columns will be added only for the first line from the file because there are no columns at point to time. And values of the first line from the file will be added to the table successfully.
After that it will not add new columns and when you try to add values to the row you will get exception because now the number of items in the line are different than the number of columns in the table.
So logically you need to check if the number of items in the line is greater than the current number of columns in the datatable. And if yes, then add those extra number of columns in the datatable.
And also instead of using dt.Rows.Add
, add the values to the row one by one.
Consider following code.
DataTable dt = new DataTable();
using (FileStream stream = File.OpenRead("logs.txt"))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = reader.ReadLine();
while (line != null)
{
string[] items = line.Split(',');
// Check if the number of items in the line is
// greater than the current number of columns in the datatable.
if(items.Length > dt.Columns.Count)
{
// Add new columns to the datatable.
for (int i = dt.Columns.Count; i < items.Length; i++)
{
dt.Columns.Add("Column " + i);
}
}
// Create new row
var newRow = dt.NewRow();
// Loop thru the items and add them to the row one by one.
for (var j = 0; j < items.Length; j++)
{
newRow[j] = items[j];
}
//Add row to the datatable.
dt.Rows.Add(newRow);
line = reader.ReadLine();
}
// Bind datatable to the gridview.
dataGridView1.DataSource = dt;
}
}
This should help you resolve your issue.
来源:https://stackoverflow.com/questions/52866098/delimited-text-to-datatable