对于你们许多人来说这似乎是一个简单的问题,但是我想要做的是我在阅读之后使用StreamReader
(ASP.net& C#)在点击事件上阅读文本文件文本文件我用','分隔符分隔每一行,然后它的每一部分我存储在Datatable's
列,然后将数据表绑定到我的gridview,我的问题是我写了代码但我得到空gridview像这样
Gridviews我从设计师autogeneratecolumns="false"
我的代码是
protected void readfile_Click(object sender, EventArgs e)
{
string line;
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))
{
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(',');
dt.Rows.Add();
for (int i = 0; i < parts.Length; i++)
{
dt.Columns.Add();
dt.Rows[0][i] = parts[i];
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
}
sr.Close();
}
我的文本文件有数据
1,1,4,2,"#",Description1
5,5,4,2,"#",Description2
3,3,6,3,"#",Description3
2,2,4,2,"#",Description4
4,5,4,2,"#",Description5
希望你能得到我想要的东西。
答案 0 :(得分:2)
这样的事情怎么样:
protected void readfile_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Row No.");
table.Columns.Add("Col No.");
table.Columns.Add("Width");
table.Columns.Add("Height");
table.Columns.Add("Image URL");
table.Columns.Add("Description");
using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))
{
while (!sr.EndOfStream)
{
string[] parts = sr.ReadLine().Split(',');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);
}
}
MyGridView.DataSource = table;
MyGridView.DataBind();
}
答案 1 :(得分:1)
for
- 循环DataColumn
移动代码
DataTable.NewRow
方法DataRow
您的代码应该是这样的:
DataTable dt = new DataTable();
dt.Columns.Add("Row No", typeof(Int32));
dt.Columns.Add("Col No", typeof(Int32));
dt.Columns.Add("Width", typeof(Int32));
dt.Columns.Add("Height", typeof(Int32));
dt.Columns.Add("ImageUrl", typeof(String));
dt.Columns.Add("Description", typeof(String));
using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))
{
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(',');
var row = dt.NewRow();
for (int i = 0; i < parts.Length; i++)
{
row[i] = parts[i];
}
// important thing!
dt.Rows.Add(row);
}
sr.Close();
}
MyGridView.DataSource = dt;
MyGridView.DataBind();
答案 2 :(得分:1)
使用以下代码
将列添加到datatableDataTable dt = new DataTable();
dt.Columns.Add("Row No", typeof(Int32));
dt.Columns.Add("Col No", typeof(Int32));
dt.Columns.Add("Width", typeof(Int32));
dt.Columns.Add("Height", typeof(Int32));
dt.Columns.Add("ImageUrl", typeof(String));
dt.Columns.Add("Description", typeof(String));
在填充数据表中的所有行后,在while循环
之后绑定数据表(dt)using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))
{
while ((line = sr.ReadLine()) != null)
{
string[] parts = line.Split(',');
var dr = dt.NewRow(); //use newrow to create new row
for (int i = 0; i < parts.Length; i++)
{
dr[i] = parts[i];
}
dt.Rows.Add(dr); //add row to datatable now
}
sr.Close();
}
//bind datatable to Gridview after we load file into dt
MyGridView.DataSource = dt;
MyGridView.DataBind();