Hello,
I am working on making a web application that will be connected to multiple servers to retrieve error logs. The error logs are written to a text file. Essentially I would like text file data to show on the webpage and enable sorting. The code that I am currently working with has NO errors but it only executes once and does not give me all the data in the text file.
aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisplayTextFile.aspx.cs" Inherits="CSV_to_Browser.DisplayTextFile" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" OnSorting="GridView1_Sorting"></asp:GridView>
</div>
</form>
</body>
</html>
aspx.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Diagnostics;
namespace CSV_to_Browser
{
public partial class DisplayTextFile : System.Web.UI.Page
{
private string SortDirection = "ASC";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string spath = Server.MapPath("~/App_Data/Book1.txt");
DataTable dt = ConvertCSVtoDataTable(spath);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["tables"] = dt;
}
}
public DataTable ConvertCSVtoDataTable(string strFilePath)
{
StreamReader sr = new StreamReader(strFilePath);
string[] headers = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
Debug.WriteLine(i.ToString());
}
dt.Rows.Add(dr);
break;
}
return dt;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["tables"] != null)
{
DataTable dt = (DataTable)ViewState["tables"];
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + SortDirection;
GridView1.DataSource = dt;
GridView1.DataBind();
}
SetSortDirection(SortDirection);
}
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
{
SortDirection = "DESC";
}
else
{
SortDirection = "ASC";
}
}
}
}
Can someone please help me with this issue?
Regards,
Gagan Marwah