As we know we all deal with different types of reports, maybe its transaction report, balance sheet, income expense statements, etc. All these reports have certain fixed format. Most of the reports have headers for each category of transactions.
Now here is the code to fill data table with such type of data and show it in GridView. Later we can fill this data in database.
- using System;
-
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class ReadTextFile : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
- protected void btnRead_Click(object sender, EventArgs e)
- {
- gridbind();
- }
- protected void gridbind()
- {
- DataTable dt = new DataTable();
- string path = Server.MapPath("~/Marketing.txt");
- if (!string.IsNullOrEmpty(path))
- {
- string[] readText = File.ReadAllLines(path);
-
- List<string> rows = readText.ToList<string>();
-
- DataColumn dc;
- string [] headers=rows[0].Split(new string[]{ "," },StringSplitOptions.None);
- foreach (string s in headers)
- {
- dc = new DataColumn(s, typeof(System.String));
-
- dt.Columns.Add(dc);
- }
- rows.RemoveAt(0);
- rows.RemoveAll(u => !u.Contains("\""));
- rows.RemoveAll(u => u.Contains("Totals"));
- DataRow dr;
- foreach (string s in rows)
- {
- string[] values = s.Split(new string[] { "\"" }, StringSplitOptions.None);
- dr = dt.NewRow();
- for (int i = 0; i < headers.Count(); i++)
- {
- dr[i] = values[i].Replace(",", "");
-
- }
- dt.Rows.Add(dr);
- }
- }
- grdData.DataSource = dt;
- grdData.DataBind();
- }
- }