【问题标题】:How to show Text in the text file separated by commas in a DataRow or a GridView in c#如何在 C# 中的 DataRow 或 GridView 中以逗号分隔的文本文件中显示文本
【发布时间】:2011-09-30 15:01:33
【问题描述】:

我已经用 C# 创建了一个应用程序。我想在 DataRow 或 GridView 中显示以逗号分隔的文本文件中的文本。

我正在使用此代码在列表框中显示文本

private void button1_Click(object sender, EventArgs e)
{
    var file = File.OpenText("C:\\File.txt"); 
    string line;
    bool flag = true;
    while ((line = file.ReadLine()) != null)
    {
        listBox1.Items.Add(new { srno= line, Date= "descr", Time= DateTime.Now ,symbol = Symbol  });
    }
}

但其他人不太了解它的显示内容。我想显示这样的内容

查看此链接http://i.stack.imgur.com/LEmdz.jpg

如果有人可以帮助我,将不胜感激。

提前致谢。

【问题讨论】:

  • 你见过Mr. String.Split吗?
  • 是的,我知道拆分方法,但是如何在 gridview 中显示单词

标签: c# winforms csv datagridview


【解决方案1】:

愚蠢的我看起来这是 WinForms 而不是 asp.net。被重新标记了。那我把这个留给别人吧。

您需要将文件转入DataTablehttp://www.akamarketing.com/blog/256-csv-datatable.html 有一个很好的例子

这更像是一种通用方法。

这是一个未经测试的示例,您可以尝试解决。

DataTable dataTable = new DataTable();
dataTable.Columns.Add("Srno");
dataTable.Columns.Add("Date");
dataTable.Columns.Add("Time");
dataTable.Columns.Add("Symbol");

while ((line = file.ReadLine()) != null)
{
    DataRow row = dataTable.NewRow();
    string[] s =  line.Split(',');
    row["Srno"] = s[0];
    row["Date"] = s[1];
    row["Time"] = s[2];
    row["Symbol"] = s[3];
}

//Add to your GridView that is in your aspx file
gridView.DataSource = dataTable;
gridView.DataBind();

【讨论】:

  • 可能不会。我发布后,您将其重新标记为 Winforms。
  • 不是我,但真的很抱歉你能不能给我winforms的代码
  • 尝试将其切换到 DataGridView for WinForms。我不太了解Winforms。不幸的是
【解决方案2】:

定义一个类(比如Foo),它有四个公共properties - srno、日期、时间和符号。使用String.Split 方法解析逗号分隔的字符串,构造一个Foo 类的对象并将其附加到List<Foo>。最后将List<Foo>对象绑定到GridView控件。

演示:

public class Foo
{
  public string SrNo {get;set;}
  public string Date {get;set;}
  public string Time {get;set;}
  public string Symbol {get;set;}
}

List<Foo> list=new List<Foo>();

while ((line = file.ReadLine()) != null)
{
    string []ar = line.Split(',');
    list.Add(new Foo()
       {
         SrNo=ar[0],
         Date=ar[1],
         Time=ar[2],
         Symbol=ar[3]
       });
}
//Bind the list
dataGridView1.DataSource=list;

【讨论】:

  • @GmBasha - 这是网络应用还是 winform?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多