Gm Basha
Gm Basha

Reputation: 53

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

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, Date= "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 https://i.sstatic.net/LEmdz.jpg

There would be great appreciation if someone could help me.

Thanks In Advance.

Upvotes: 0

Views: 1155

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94653

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;

Upvotes: 0

Kirk
Kirk

Reputation: 16265

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

Upvotes: 2

Related Questions