开发者

How to show Text in the text file separated by commas in a DataRow or a GridView in c#

开发者 https://www.devze.com 2023-04-10 07:37 出处:网络
I have created an application in C#. I want to display the text in the text file separated by commas in a DataRow or a GridView.

I have created an application in C#. I want to display the text in the text file separated by commas in a DataRow or a GridView.

I am using this code to display the text in a listbox

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, Da开发者_如何学JAVAte= "descr", Time= DateTime.Now ,symbol = Symbol  });
    }
}

But its not well for others to understand what its displaying.i want to display something like this

check this link http://i.stack.imgur.com/LEmdz.jpg

There would be great appreciation if someone could help me.

Thanks In Advance.


Silly me looks like this is WinForms not asp.net. Got retagged. I'll leave this here for someone else then.

You'll want to turn the file in to a DataTable. There is a decent example of this at http://www.akamarketing.com/blog/256-csv-datatable.html

It's more of a generic approach than anything.

Here is an untested example you could try to work through.

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();


Define a class (say Foo) having four public properties - srno, Date,Time, and symbol. Use String.Split method to parse the comma separated string, constructs an object of Foo class and append it to List<Foo>. Finally bind the List<Foo> object to the GridView control.

Demo:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号