我正在尝试使用自动代码将数据从文本文件导入网格视图:
DataTable dt = new DataTable();
using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log")))
{
string line;
while ((line = tr.ReadLine()) != null)
{
string[] items = line.Trim().Split(' ');
if (dt.Columns.Count == 0)
{
// Create the data columns for the data table based on the number of items
// on the first line of the file
for (int i = 0; i < items.Length; i++)
dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
}
dt.Rows.Add(items);
}
//show it in gridview
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
我的文件就像:
A B C
E F D C C
E D D D
D P
然后我收到以下错误
输入数组比c#application
中此表中的列数长
答案 0 :(得分:1)
您似乎已根据第一行创建//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has value for description
db.insert("Items", null, contentValues);//Items is table name
db.close();
}
columns
,但第二行有更多列,然后第一行 >。请根据table
列检查以下代码。
CODE:
MAX
在您的数据中,某些行有DataTable dt = new DataTable();
List<string[]> list = new List<string[]>();
int maxItem = 0;
using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log")))
{
string line;
while ((line = tr.ReadLine()) != null)
{
string[] items = line.Trim().Split(' ');
if (maxItem <= items.Count())
{
maxItem = items.Count();
}
list.Add(items);
}
for (int i = 0; i < maxItem; i++)
dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
foreach (var items in list)
{
dt.Rows.Add(items);
}
//show it in gridview
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
。因此,您必须在代码中检查empty
行。
输出您的数据:
答案 1 :(得分:1)
您应该在所需的列数(Split(' ')
之后)更大而非实际(dt.Columns.Count
)之后添加新列:
// File.ReadLines is easier to read and maintain
var items = File
.ReadLines(@"d:\My File3.log") // single \ since we have verbatim string @
//.Where(line => !string.IsNullOrWhiteSpace(line)) // if you want to remove empty lines
.Select(line => line.Trim().Split(' '));
DataTable dt = new DataTable();
foreach (var line in items) {
// Do we want extra columns?
while (line.Length > dt.Columns.Count)
dt.Columns.Add(new DataColumn($"Column {dt.Columns.Count}", typeof(string)));
dt.Rows.Add(line);
}
GridView1.DataSource = dt;
GridView1.DataBind();