ASP.net gridview, autorefresh, txt as source and maintain scroll position - c#

I want this gridview to emulate a console, the text file I have is a server console log.
I want it to:
*Refresh when the file changes.(thus the timer)
*Scroll bar position maintained when updated, unless at bottom.
*When scroll bar position is at the bottom,stay at the bottom after databind update.
Current Problem: On timer, databind() moves the scrollbar position back to the top, and with a refresh so often you can't even scroll down at all.
Here is my current code. Thank you for your help!
asp.net
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TEST CONSOLE.aspx.cs" Inherits="WebApplication1.TEST_CONSOLE" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="30" ontick="Timer1_Tick"></asp:Timer>
<div style="width: 100%; height: 400px; overflow: scroll">
<asp:GridView ID="GridView1" runat="server" MaintainScrollPositionOnPostback="true">
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace WebApplication1
{
public partial class TEST_CONSOLE : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StreamReader objStreamReader = new StreamReader(Server.MapPath("TextFile.txt"));
var arrText = new List<string>();
// ' Loop through the file and add each line to the ArrayList
while( objStreamReader.Peek() >= 0){
arrText.Add(objStreamReader.ReadLine());
}
//' Close the reader
objStreamReader.Close();
//' Bind the results to the GridView
GridView1.DataSource = arrText;
GridView1.DataBind();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
GridView1.DataBind();
}
}
}

Found most of answer here
http://forums.asp.net/t/1220070.aspx?how+to+maintain+scroll+position+in+gridview+or+datagrid+during+postback
using ajax and these two functions
function Func() {//document.getElementById("hdnScrollTop").value
document.getElementById("divScroll").scrollTop = document.getElementById("hdnScrollTop").value;
}
function Func2() {
var s = document.getElementById("divScroll").scrollTop;
document.getElementById('hdnScrollTop').value = s;

Related

How to Update the value of textbox in asp.net using c#?

I have this program in asp.net using C#
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="first" runat="server">
Text Boxes
<asp:TextBox ID="txtnr" runat="server"></asp:TextBox><br />
<asp:Button ID="btnxt1" runat="server" Text="Next" onclick="btnxt1_Click"/><br />
</div>
<div id="second" runat="server">
<asp:Table ID="tbl" runat="server"></asp:Table>
<asp:Button ID="btnx2" runat="server" Text="Next" onclick="btnx2_Click"/><br />
</div>
<div id="third" runat="server">
<asp:Label ID="lblxx" runat="server" Text=""></asp:Label><br />
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
static int numr = 0;
static TableHeaderCell[] tc2;
static TextBox[] txtb;
protected void Page_Load(object sender, EventArgs e){}
protected void btnxt1_Click(object sender, EventArgs e)
{
numr = int.Parse(txtnr.Text);
TableHeaderRow tr;
tc2 = new TableHeaderCell[numr];
txtb = new TextBox[numr];
for (int i = 0; i < numr; i++)
{
tr = new TableHeaderRow();
tc2[i] = new TableHeaderCell();
txtb[i] = new TextBox();
txtb[i].Text = "w";
tc2[i].Controls.Add(txtb[i]);
tr.Controls.Add(tc2[i]);
tbl.Controls.Add(tr);
}
}
protected void btnx2_Click(object sender, EventArgs e)
{
for (int i = 0; i < numr; i++)
lblxx.Text += txtb[i].Text+"<br/>";
}
}
Program steps:
enter number of text-boxes to appear (say = 4) and click 'Next'
four text-boxes will appear (the program sets the value of textbox = "w",to understand the problem)
user can set other value for the text for the four text boxes (say: 1 , 2 , 3 , 4) then click next
finally, the program print the values of text boxes, but the problem is the program
will print: wwww not "1234" :( ??
How to fix this problem??
The problem is due to the fact that dynamic controls (like yours) do not automatically maintain their state after a post back and you should handle it on your own.
Please follow this link for a very similar question and then this link for the corresponding solution.

ScriptManager.RegisterStartupScript not triggered second time inside updatepanel

My aspx page
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
My CS page
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
When I click the "Play" button for first time, OpenPlayerWindow() or OpenPlayerWindowForError() opens accoding to the condition. And if I click the button again, "btnPlay" is called but not any of JS function.
If I refresh the page, it works perfect again.
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</span>
I am not able to write this code in comments hence I am writing this as an answer. The following is the code which I have with me. Please copy-paste it in a separate project and try if it works.
Also if I am not replicating this issue properly(not written the code correctly) then please comment.
If the code is okay with you and if it works on a separate project then there probably is a problem in some other code which is not shown in your question.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Practice_Web.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<%--It works if I keep the script here also--%>
</div>
</form>
</body>
<script type="text/javascript">
function OpenPlayerWindow() {
alert("Thanks!");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!");
}
</script>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practice_Web
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is just to simulate the condition part of the original code
if (Session["condition"] == null)
Session["condition"] = false;
else
Session["condition"] = !Convert.ToBoolean(Session["condition"]);
}
protected void btnPlay(object sender, EventArgs e)
{
bool condition = Convert.ToBoolean(Session["condition"]);
if (condition)
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
}
}
try below code
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(this, GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}

ASP .NET: CustomValidator doesn't launch its ServerValidate method

the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MyWebForm.aspx.cs" Inherits="MyWebApplication.MyWebForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 334px">
<form id="form1" runat="server">
<div style="height: 338px">
<asp:TextBox ID="MyTextBox" runat="server" AutoPostBack="True"></asp:TextBox>
<br />
<asp:CustomValidator ID="MyCustomValidator" runat="server"
ControlToValidate="MyTextBox" ErrorMessage="My error message"
onservervalidate="Foo2"></asp:CustomValidator>
</div>
</form>
</body>
</html>
the C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWebApplication
{
public partial class MyWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool Foo1(string bar)
{
if (bar == "bar")
return true;
return false;
}
protected void Foo2(object source, ServerValidateEventArgs args)
{
args.IsValid = this.Foo1(this.MyTextBox.Text);
} // breakpoint
}
}
I set breakpoint in the Foo2 function (comment), but debugger hasn't visited it. I tried writing diffrent text, not writting anything and writting "bar" and pushing enter and tab after that, but it still doesn't work. I mean text changing action. Is it possible?
There's no submit button. You need to add a button to submit the form, which will then trigger page validation.
<asp:Button runat="server" id="myButton" Text="Submit" />

how to set html tag dir attribute from rtl to ltr and vice versa programmatically in c sharp

I'm trying to build a multilingual web site on asp.net and i need to set html tag dir attribute from rtl to ltr and vice versa programmatically in c sharp.
For now i have 3 languages english, hebrew and russian and i need to switch between them.
I need to change direction of a site every time i change from ltr to rtl language and from rtl to ltr language
here the example of my masterpage
please help me
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="CSS/Site-RTL.css" rel="stylesheet" type="text/css" />
</head>
<body id="html" runat="server">
<form id="theForm" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</div>
<div style="margin-top: 20px;">
<asp:LinkButton ID="btnSetEnglish" runat="server" Text="English" CommandArgument="en-GB"
OnClick="RequestLanguageChange_Click"></asp:LinkButton>
<asp:LinkButton ID="btnSetHebrew" runat="server" Text="Hebrew" CommandArgument="he-IL"
OnClick="RequestLanguageChange_Click"></asp:LinkButton>
<asp:LinkButton ID="btnSetRussian" runat="server" Text="Russian" CommandArgument="ru-RU"
OnClick="RequestLanguageChange_Click"></asp:LinkButton>
</div>
<div>
<asp:SiteMapDataSource ID="smdsMaster" runat="server" OnDataBinding="Page_Load" />
<asp:Menu ID="MenuMaster" runat="server" CssClass="menu" DataSourceID="smdsMaster"
Orientation="Horizontal" StaticDisplayLevels="2" StaticSubMenuIndent="16px" MaximumDynamicDisplayLevels="1">
<DataBindings>
<asp:MenuItemBinding DataMember="SiteMapNode" NavigateUrlField="Url" />
</DataBindings>
</asp:Menu>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
here a code behind a master page
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Localization.Classes;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RequestLanguageChange_Click(object sender, EventArgs e)
{
LinkButton senderLink = sender as LinkButton;
//store requested language as new culture in the session
if (senderLink.CommandArgument == "he-IL")
{
// some code
}
else
{
// some code
}
Session[Global.SESSION_KEY_CULTURE] = senderLink.CommandArgument;
//reload last requested page with new culture
Server.Transfer(Request.Path);
}
}
In your code behind:
this.html.Attributes.Add("dir", "ltr");
An alternative, if this is not working is to place the attribute directly on the tag and use a property to populate it:
<body dir="<%:Dir%>">
public string Dir { get; set; }
// Set Dir in the on click event
protected void RequestLanguageChange_Click(object sender, EventArgs e)
{
LinkButton senderLink = sender as LinkButton;
//store requested language as new culture in the session
if (senderLink.CommandArgument == "he-IL")
{
Dir = "rtl";
}
else
{
Dir = "ltr";
}
Session[Global.SESSION_KEY_CULTURE] = senderLink.CommandArgument;
//reload last requested page with new culture
Server.Transfer(Request.Path);
}

Find A Control (Inside Master Page) From Content Page, Error = NullReferenceException

Please See The Simple Example Below For Understanding My situation.
(Attention To Comments Inside Codes)
Master Page (ASPX) :
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="NiceFileExplorer.Site1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<span runat="server" id="SummaryContainer">
<asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Count :"
ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Count-Today"></asp:Label>
<span style="color: white;"> | </span>
<asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Size :"
ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Size-Today"></asp:Label>
</span>
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" ViewStateMode="Inherit" ClientIDMode="Static">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
as you see i set ClientIDMode="Static".
Master Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class Site1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
SummaryContainer.DataBind();
}
protected string Download_Count_By_UserID_Today()
{
//Read New Count From DataBase
//return Count;
return "Test";
}
protected string Download_Size_By_UserID_Today()
{
//Read New Size From DataBase
//return Size;
return "Test";
}
}
}
Content Page (ASPX) :
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NiceFileExplorer.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
Conntent Page
</asp:Content>
Content Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyMethod();
}
private void MyMethod()
{
//Add New Downloaded File Info To DataBase(); -> For Getting Count And Size Of Them Per Day
//Here I Wand To Access Master Page Controls And Update Count And Size Lables
//So, I Tried Codes Below Without Any Results -> How Can I Fix This ?
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind();
SummaryContainer.InnerHtml = "<h2>Hello World</h2>";
//After Update Those Lables Failed, I test the codes Below With Null Execption Error -> How Can I Fix This ?
var lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
DwonloadFile();
}
private void DwonloadFile()
{
//A Class (Method) That Shows Download Window To My Users, So Page_Load Of Master Will Never Fire...
//And This Is The Reason That I want to update count & size lables from content page
}
}
}
i want to DataBind SummaryContainer(a span) from content page's code-behind.
so i tried the codes below :
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind():
but i can not see new results.
After That Fail I tried to find a label's text(that label is inside Master) from content page code behind for test like below : var
lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
but i have System.NullReferenceException ERROR :
Object reference not set to an instance of an object.
how can i fix that error and force that span to show me new results?
thanks in advance
In a project I used an interface on the masterpage:
((IMasterPage)Page.Master).MyProperty = "test";
But in your case, personally instead of putting all that on the master page, I'd put your SummaryContainer into a UserControl, and have another ContentPlaceHolder.
Then the Page_Load method will be able to access the properties, and on future pages you could have different summary info by filling that first PlaceHolder with a different UserControl.
Also debugging stupid errors, is the Null exception being thrown at .Master.FindControl or at lbl.Text?
I'm unable to debug it for myself right now, but would it be due to the page life cycle, namely that Content Page Load comes before Master Page Load?

Categories