Showing posts with label event. Show all posts
Showing posts with label event. Show all posts

Monday, March 26, 2012

NEWBIE: passing error to javascript alert

Hello,
is there a way call a javascript function directly from within asp
page?
Example, here is page load event in C#

protected void Page_Load(object sender, EventArgs e){

// create error
int Var0 = 0;
try {
int iVar1 = 8/Var0;
}

catch (Exception ex){

string sExMsg = ex.Message;

//javascript works fine with string constant
Response.Write("<script type='text/javascript'>alert('In Catch');</
script>");

//can write error to page no problem
Response.Write(sExMsg);

// would like a popup with error
Response.Write("<script language='javascript'>doAlert(" + sExMsg +
");</script>");
Response.Write("<script language='javascript'>function doAlert(sExMsg)
{alert(sExMsg);}</script>");

//write error to log since I can't pop-it-up
//StreamWriter sw = File.AppendText(Server.MapPath("~/error.log"));
//sw.WriteLine(sExMsg);
//sw.Close();

}

}

Any help for a newbie is appreciated

Gi<gijeet@.yahoo.comwrote in message
news:1193076186.658316.66870@.e9g2000prf.googlegrou ps.com...

Quote:

Originally Posted by

Any help for a newbie is appreciated


ClientScript.RegisterStartupScript(GetType(), "error", "alert('In Catch');",
true);

--
Mark Rae
ASP.NET MVP
http://www.markrae.net
ClientScript.RegisterStartupScript(GetType(), "error", "alert('In Catch');",

Quote:

Originally Posted by

true);


Thanks but not sure how to use this. Where do I put this? class
level before page load event? within page load? do I need a
RegisterStartupScript for each alert I wish to use?

Gi
<gijeet@.yahoo.comwrote in message
news:1193079485.948563.150590@.i38g2000prf.googlegr oups.com...

Quote:

Originally Posted by

Quote:

Originally Posted by

>ClientScript.RegisterStartupScript(GetType(), "error", "alert('In
>Catch');",
>true);


>
Thanks but not sure how to use this. Where do I put this?


Wherever you like, so long as you don't Redirect from the page...

Basically, it will send down the JavaScript to run after the page had
loaded...

Quote:

Originally Posted by

do I need a RegisterStartupScript for each alert I wish to use?


Yes.

Incidentally, why are you actually doing this...?

--
Mark Rae
ASP.NET MVP
http://www.markrae.net
Incidentally, why are you actually doing this...?
basically for debugging. I don't like response.writes and I'm trying
to learn javascript. but if you know of a better way to popup alerts,
let me know.
use the debugger to debug. alert debugging is asp classic style :)

"gijeet@.yahoo.com" wrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

Incidentally, why are you actually doing this...?


basically for debugging. I don't like response.writes and I'm trying
to learn javascript. but if you know of a better way to popup alerts,
let me know.
>
>
>
>
>
>


This can help you:
How to Pass Messages and Actions between Server and Client
http://usableasp.net/DeveloperPage...erAndClient.htm
--
Eliyahu Goldin,
Software Developer
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net
<gijeet@.yahoo.comwrote in message
news:1193076186.658316.66870@.e9g2000prf.googlegrou ps.com...

Quote:

Originally Posted by

Hello,
is there a way call a javascript function directly from within asp
page?
Example, here is page load event in C#
>
protected void Page_Load(object sender, EventArgs e){
>
// create error
int Var0 = 0;
try {
int iVar1 = 8/Var0;
}
>
catch (Exception ex){
>
string sExMsg = ex.Message;
>
>
//javascript works fine with string constant
Response.Write("<script type='text/javascript'>alert('In Catch');</
script>");
>
//can write error to page no problem
Response.Write(sExMsg);
>
// would like a popup with error
Response.Write("<script language='javascript'>doAlert(" + sExMsg +
");</script>");
Response.Write("<script language='javascript'>function doAlert(sExMsg)
{alert(sExMsg);}</script>");
>
//write error to log since I can't pop-it-up
//StreamWriter sw = File.AppendText(Server.MapPath("~/error.log"));
//sw.WriteLine(sExMsg);
//sw.Close();
>
}
>
}
>
Any help for a newbie is appreciated
>
Gi
>


"Eliyahu Goldin" <REMOVEALLCAPITALSeEgGoldDinN@.mMvVpPsS.orgwrote in
message news:%23DynzGXFIHA.4880@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

This can help you:
How to Pass Messages and Actions between Server and Client
http://usableasp.net/DeveloperPage...erAndClient.htm


Not much use in this particular case, though, as the OP's requirements for
this were for debugging a la ASP Classic...

--
Mark Rae
ASP.NET MVP
http://www.markrae.net

newbie: Problem getting the querystring!

hey

asp.net 2.0

in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();

The URL has a querystring, for example like this: Default.aspx?user=newbie

But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"

What am I doing wrong here?

JeffJeff wrote:

Quote:

Originally Posted by

hey
>
asp.net 2.0
>
in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();
>
The URL has a querystring, for example like this: Default.aspx?user=newbie
>
But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"
>
What am I doing wrong here?
>
Jeff


string username = Request.QueryString["user"];
Best bet is to access the querystring collection directly. I'm not sure if
it's something that can do like this, as normally a lot of collections are
copied using the CopyTo method, but this is usually done for arrays not
specialized collections.

Your best bet though is to access it directly from the querystring. Also,
don't use positional identifiers to determine a parameter, it's too easy to
change the order that things will appear in so it's best to use the keyname
instead. Also, don't forget to test for null first or else it'll bomb out
when you run into a case where it's an empty value, that's the most common
gatcha when using the querystring.

--
Hope this helps,
Mark Fitzpatrick
Former Microsoft FrontPage MVP 199?-2006

"Jeff" <it_consultant1@.hotmail.com.NOSPAMwrote in message
news:udZYNHc%23GHA.4472@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

hey
>
asp.net 2.0
>
in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();
>
The URL has a querystring, for example like this: Default.aspx?user=newbie
>
But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"
>
What am I doing wrong here?
>
Jeff
>


Default.aspx?user=newbie
string username = Request.QueryString["user"]; gives username a NULL
value...

Any more suggestions?

"Simon Rigby" <google@.simonrigby.co.ukwrote in message
news:1161951708.089584.264150@.m7g2000cwm.googlegro ups.com...

Quote:

Originally Posted by

>
Jeff wrote:

Quote:

Originally Posted by

>hey
>>
>asp.net 2.0
>>
>in the page_load event of a web page I place this code:
>NameValueCollection parameters = Request.QueryString;
>string username = parameters[0].ToString();
>>
>The URL has a querystring, for example like this:
>Default.aspx?user=newbie
>>
>But this code don't get the querystring, the parameters collection gets
>no
>entries from this line "NameValueCollection parameters =
>Request.QueryString;"
>>
>What am I doing wrong here?
>>
>Jeff


>
string username = Request.QueryString["user"];
>


"Jeff" <it_consultant1@.hotmail.com.NOSPAMwrote in message
news:udZYNHc%23GHA.4472@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

hey
>
asp.net 2.0
>
in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();
>
The URL has a querystring, for example like this: Default.aspx?user=newbie
>
But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"
>
What am I doing wrong here?
>
Jeff
>


I usually use the form
if Request.QueryString.Item("_o") <string.empty then
stroID = Request.QueryString.Item("_o").tostring()
end if

to get the whole collection you can use

Dim coll As NameValueCollection
coll=request.querystring

and then you can access it using coll("_o") for example

Mike
It's my own fault... I thought the URL had a querystring, but because I had
set a breakpoint and then checked the URL during debug, I didn't see the
real URL, I only saw the last URL....

"Jeff" <it_consultant1@.hotmail.com.NOSPAMwrote in message
news:udZYNHc%23GHA.4472@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

hey
>
asp.net 2.0
>
in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();
>
The URL has a querystring, for example like this: Default.aspx?user=newbie
>
But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"
>
What am I doing wrong here?
>
Jeff
>

newbie: Problem getting the querystring!

hey
asp.net 2.0
in the page_load event of a web page I place this code:
NameValueCollection parameters = Request.QueryString;
string username = parameters[0].ToString();
The URL has a querystring, for example like this: Default.aspx?user=newbie
But this code don't get the querystring, the parameters collection gets no
entries from this line "NameValueCollection parameters =
Request.QueryString;"
What am I doing wrong here?
JeffJeff wrote:
> hey
> asp.net 2.0
> in the page_load event of a web page I place this code:
> NameValueCollection parameters = Request.QueryString;
> string username = parameters[0].ToString();
> The URL has a querystring, for example like this: Default.aspx?user=newbie
> But this code don't get the querystring, the parameters collection gets no
> entries from this line "NameValueCollection parameters =
> Request.QueryString;"
> What am I doing wrong here?
> Jeff
string username = Request.QueryString["user"];
Best bet is to access the querystring collection directly. I'm not sure if
it's something that can do like this, as normally a lot of collections are
copied using the CopyTo method, but this is usually done for arrays not
specialized collections.
Your best bet though is to access it directly from the querystring. Also,
don't use positional identifiers to determine a parameter, it's too easy to
change the order that things will appear in so it's best to use the keyname
instead. Also, don't forget to test for null first or else it'll bomb out
when you run into a case where it's an empty value, that's the most common
gatcha when using the querystring.
Hope this helps,
Mark Fitzpatrick
Former Microsoft FrontPage MVP 199...2006
"Jeff" <it_consultant1@.hotmail.com.NOSPAM> wrote in message
news:udZYNHc%23GHA.4472@.TK2MSFTNGP05.phx.gbl...
> hey
> asp.net 2.0
> in the page_load event of a web page I place this code:
> NameValueCollection parameters = Request.QueryString;
> string username = parameters[0].ToString();
> The URL has a querystring, for example like this: Default.aspx?user=newbie
> But this code don't get the querystring, the parameters collection gets no
> entries from this line "NameValueCollection parameters =
> Request.QueryString;"
> What am I doing wrong here?
> Jeff
>
Default.aspx?user=newbie
string username = Request.QueryString["user"]; gives username a NULL
value...
Any more suggestions?
"Simon Rigby" <google@.simonrigby.co.uk> wrote in message
news:1161951708.089584.264150@.m7g2000cwm.googlegroups.com...
> Jeff wrote:
> string username = Request.QueryString["user"];
>
"Jeff" <it_consultant1@.hotmail.com.NOSPAM> wrote in message
news:udZYNHc%23GHA.4472@.TK2MSFTNGP05.phx.gbl...
> hey
> asp.net 2.0
> in the page_load event of a web page I place this code:
> NameValueCollection parameters = Request.QueryString;
> string username = parameters[0].ToString();
> The URL has a querystring, for example like this: Default.aspx?user=newbie
> But this code don't get the querystring, the parameters collection gets no
> entries from this line "NameValueCollection parameters =
> Request.QueryString;"
> What am I doing wrong here?
> Jeff
>
I usually use the form
if Request.QueryString.Item("_o") <> string.empty then
stroID = Request.QueryString.Item("_o").tostring()
end if
to get the whole collection you can use
Dim coll As NameValueCollection
coll=request.querystring
and then you can access it using coll("_o") for example
Mike

Thursday, March 22, 2012

newbie--loadviewstate?

trying to make the transition from windows event model programming after 25 years to web development in general and asp.net specfically. making good progress but having hard time with the whole postback process.

in a windows form (vb.net) i can create a public variable "****" and click a button and have it increment by one in a text box (see code below)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

MessageBox.Text = ****
**** = **** + 1

End Sub

when i try to do same thing in a web form, the variable retains the same value and never increments in the textbox control--from my reading, i believe it has to do with viewstate and that i must intercept the view state of the control after every page post back--but i'm not sure that i'm understanding this correctly. this is such a basic issue to get straight that i thought i better ask this newbie question now. if someone can give me a very simple explanation of what i'm doing wrong, i'd appreciate it. i never realized the complexity of web programming--i'm ready to go back to a windows app.

thanks

daleHi,

yes, it has to do with ViewState and how ASP.NET pages process incoming web requests.

Workings are so that the Page class is recreated for every request (on initial request and on subsequent postbacks), therefore including its members which means that they can't keep their state without help of external mechanism that is, ViewState.

ViewState, state of controls on the page plus data stored to Page's own ViewState collection is saved at the end of every request and on postback it is again restored to controls and to the collection (automatically for the most part).

But, what you saw and explained is because you don't reassign the new value into the TextBox after doing the incrementing. Member variable cannot keep the state because it is recreated (it could keep if you'd create a property for it, which uses Page's ViewState collection as storage), but you can keep the state via TextBox itself. Here is an example:


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then
TextBox1.Text = 0.ToString()
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = CInt(TextBox1.Text)
TextBox1.Text = i + 1
End Sub

So basically I didn't even utilize a Page level member here, but did the incrementing solely with the TextBox. But, like I said, you could also have a property on the Page which keeps the state, the example could look like following.


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then
TextBox1.Text = TestingState.ToString()
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TestingState += 1
TextBox1.Text = TestingState.ToString()
End Sub

Public Property TestingState() As Integer
Get
Dim o As Object = ViewState("TestingState")
If o Is Nothing Then
Return 0
Else
Return CInt(o)
End If
End Get
Set(ByVal Value As Integer)
ViewState("TestingState") = Value
End Set
End Property


Hi Dale,
Web page unlike winform is stateless. It means that page object is created, initialized and destroyed on each roundtrip. To keep variables values across roundtris, you need to persist them somehow. Choices you have are: Session, ViewState, PostbackData, Database etc. For example you can do it with ViewState this way:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

MessageBox.Text = ****
Dim obj As Object = Me.ViewState.Item("****")
If (Not obj Is Nothing) Then
**** = CType(obj1,Integer)
End If
**** = **** + 1
Me.ViewState.Item("****")

End Sub


thanks teemu and leon!

your help has helped me get over this hump to the next hump waiting me..

thanks for your quick help!

dale

Friday, March 16, 2012

NewPageIndex Doesn't Get Updated in PageIndexChanging Event

We have a base class that is responsible for creating the navigation and loo
k
and feel of our applications. So all our web pages inherit from this base
page so they don't have to worry about the look and feel and navigation, onl
y
the main content. Everything has woked just fine until we converted to 2.0.
Now we have a problem with the new GridView and the paging. With the
DataGrid in 1.1, the paging worked just fine. Now with paging turned on and
the mode set to "NextPrevious" the NewPageIndex doesn't get updated in the
PageIndexChanging event. However if I change the web page to not inherit
from my base class but just from the System.web.ui.page then the paging work
s
correctly. This is a code snipit of our base class and how it loads the
controls from the derived page. I am really stumped on this one so if anyon
e
has any ideas it would be greatly appreciated.
ASPX Page:
<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<asp:GridView ID="GridView1" runat="server" AllowPaging="true"
OnPageIndexChanging="GridView1_PageIndexChanging">
<PagerSettings Mode="NextPrevious"></PagerSettings>
</asp:GridView>
Code Behind (scaled down and only showing the basics):
using System;
using System.Data;
using System.Configuration;
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 System.Data.OleDb;
public partial class _Default : MyBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
private DataSet GetDataSource()
{
OleDbConnection cn = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data
Source=C:\\Program Files\\Microsoft Visual Studio\\VB98\\nwind.mdb");
OleDbDataAdapter da = new OleDbDataAdapter("Select CompanyName,
ContactName, Address from Customers", cn);
DataSet customers = new DataSet();
da.Fill(customers, "Customers");
return customers;
}
}
public class MyBasePage : System.Web.UI.Page
{
HtmlForm objForm;
public MyBasePage()
{
objForm = new HtmlForm();
}
protected override void OnInit(System.EventArgs e)
{
BuildPage();
base.OnInit(e);
}
private void BuildPage()
{
for (int i = 0; i < this.Controls.Count; i++)
{
System.Web.UI.Control objCtrl = this.Controls[0];
objForm.Controls.Add(objCtrl);
this.Controls.Remove(objCtrl);
}
this.Controls.Add(objForm);
}
}Hi,
Thank you for your post.
First, this problem can be fixed by using following BuildPage() function:
private void BuildPage()
{
ArrayList al = new ArrayList();
foreach(Control c in Controls)
{
al.Add(c);
}
Controls.Add(objForm);
foreach(Control c in al)
{
objForm.Controls.Add(c);
}
}
Following are detailed causes:
1) The root cause of this problem is GridView's PageIndex is stored using
ASP.NET 2.0's new feature called "ControlState". See following MSDN for
more info:
http://msdn2.microsoft.com/en-us/li...atepersister.co
ntrolstate.aspx
A server control that use control state must call the
RegisterRequiresControlState method on each request because registration
for control state is not carried over from request to request during a
postback event. It is recommended that registration occur in the Init event.
GridView calls this method in its OnInit:
protected internal override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Page != null)
{
if ((this.DataKeyNames.Length > 0) &&
!this.AutoGenerateColumns)
{
this.Page.RegisterRequiresViewStateEncryption();
}
this.Page.RegisterRequiresControlState(this);
}
}
Please note that it checks for "this.Page != null" first.
2) When adding a control to a ControlCollection, it will automatically
first remove it from its old parent.Controls (if its parent is not null),
and removing a control will Unload it first!
In previous code, when we first add the GridView to objForm.Controls,
because objForm is not added to Page.Controls yet, the "this.Page != null"
will be false for the GridView, thus not calling the
RegisterRequiresControlState.
So, what we are doing now is first adding the objForm to Page.Controls,
then add the remaining controls to objForm, this will ensure GridView's
ControlState is persisted.
As a side note, in ASP.NET 2.0, we have a new feature called MasterPage
which is exactly for the purpose of keeping a consistent look and feel for
the entire website.
Hope this helps. Please feel free to post here if anything is unclear.
Regards,
Walter Wang
Microsoft Online Community Support
========================================
==========
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
========================================
==========
This posting is provided "AS IS" with no warranties, and confers no rights.
Walter, thanks for the reply. That fixed it. However, this brings up
another question. We currently use this base page for our 1.1 apps. We hav
e
some groups in our company that are trying to use our base page compiled wit
h
1.1 in their 2.0 web apps. This is the first issue we have ran into with
trying to use our 1.1 base code in a 2.0 app. If I go change our base page
to load the form into the page object before I load any controls into the
form collection, will this cause any problems with any of the 1.1 controls?
Also, in response to your side note, I wanted to use the Master pages but
unfortunately our base page is in a class library in a seperate assembly
rather than in the web application itself so there was no way to use the
master pages. At least this is what Microsoft told us. We distribute this
assembly throughout our company to let other development teams use in order
to have the corporate look and feel.
"Walter Wang [MSFT]" wrote:

> Hi,
> Thank you for your post.
> First, this problem can be fixed by using following BuildPage() function:
> private void BuildPage()
> {
> ArrayList al = new ArrayList();
> foreach(Control c in Controls)
> {
> al.Add(c);
> }
> Controls.Add(objForm);
> foreach(Control c in al)
> {
> objForm.Controls.Add(c);
> }
> }
> Following are detailed causes:
> 1) The root cause of this problem is GridView's PageIndex is stored using
> ASP.NET 2.0's new feature called "ControlState". See following MSDN for
> more info:
> [url]http://msdn2.microsoft.com/en-us/library/system.web.ui.pagestatepersister.co[/ur
l]
> ntrolstate.aspx
> A server control that use control state must call the
> RegisterRequiresControlState method on each request because registration
> for control state is not carried over from request to request during a
> postback event. It is recommended that registration occur in the Init even
t.
> GridView calls this method in its OnInit:
> protected internal override void OnInit(EventArgs e)
> {
> base.OnInit(e);
> if (this.Page != null)
> {
> if ((this.DataKeyNames.Length > 0) &&
> !this.AutoGenerateColumns)
> {
> this.Page.RegisterRequiresViewStateEncryption();
> }
> this.Page.RegisterRequiresControlState(this);
> }
> }
> Please note that it checks for "this.Page != null" first.
> 2) When adding a control to a ControlCollection, it will automatically
> first remove it from its old parent.Controls (if its parent is not null),
> and removing a control will Unload it first!
> In previous code, when we first add the GridView to objForm.Controls,
> because objForm is not added to Page.Controls yet, the "this.Page != null"
> will be false for the GridView, thus not calling the
> RegisterRequiresControlState.
> So, what we are doing now is first adding the objForm to Page.Controls,
> then add the remaining controls to objForm, this will ensure GridView's
> ControlState is persisted.
> As a side note, in ASP.NET 2.0, we have a new feature called MasterPage
> which is exactly for the purpose of keeping a consistent look and feel for
> the entire website.
> Hope this helps. Please feel free to post here if anything is unclear.
> Regards,
> Walter Wang
> Microsoft Online Community Support
> ========================================
==========
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> ========================================
==========
> This posting is provided "AS IS" with no warranties, and confers no rights
.
>

NewPageIndex Doesnt Get Updated in PageIndexChanging Event

We have a base class that is responsible for creating the navigation and look
and feel of our applications. So all our web pages inherit from this base
page so they don't have to worry about the look and feel and navigation, only
the main content. Everything has woked just fine until we converted to 2.0.
Now we have a problem with the new GridView and the paging. With the
DataGrid in 1.1, the paging worked just fine. Now with paging turned on and
the mode set to "NextPrevious" the NewPageIndex doesn't get updated in the
PageIndexChanging event. However if I change the web page to not inherit
from my base class but just from the System.web.ui.page then the paging works
correctly. This is a code snipit of our base class and how it loads the
controls from the derived page. I am really stumped on this one so if anyone
has any ideas it would be greatly appreciated.

ASPX Page:

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<asp:GridView ID="GridView1" runat="server" AllowPaging="true"
OnPageIndexChanging="GridView1_PageIndexChanging">
<PagerSettings Mode="NextPrevious"></PagerSettings>
</asp:GridView
Code Behind (scaled down and only showing the basics):

using System;
using System.Data;
using System.Configuration;
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 System.Data.OleDb;

public partial class _Default : MyBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}

protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}

private DataSet GetDataSource()
{
OleDbConnection cn = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data
Source=C:\\Program Files\\Microsoft Visual Studio\\VB98\\nwind.mdb");
OleDbDataAdapter da = new OleDbDataAdapter("Select CompanyName,
ContactName, Address from Customers", cn);
DataSet customers = new DataSet();
da.Fill(customers, "Customers");
return customers;
}
}

public class MyBasePage : System.Web.UI.Page
{
HtmlForm objForm;

public MyBasePage()
{
objForm = new HtmlForm();
}

protected override void OnInit(System.EventArgs e)
{
BuildPage();
base.OnInit(e);
}

private void BuildPage()
{
for (int i = 0; i < this.Controls.Count; i++)
{
System.Web.UI.Control objCtrl = this.Controls[0];
objForm.Controls.Add(objCtrl);
this.Controls.Remove(objCtrl);
}
this.Controls.Add(objForm);
}
}Hi,

Thank you for your post.

First, this problem can be fixed by using following BuildPage() function:

private void BuildPage()
{
ArrayList al = new ArrayList();
foreach(Control c in Controls)
{
al.Add(c);
}
Controls.Add(objForm);

foreach(Control c in al)
{
objForm.Controls.Add(c);
}
}

Following are detailed causes:

1) The root cause of this problem is GridView's PageIndex is stored using
ASP.NET 2.0's new feature called "ControlState". See following MSDN for
more info:
http://msdn2.microsoft.com/en-us/li...atepersister.co
ntrolstate.aspx

A server control that use control state must call the
RegisterRequiresControlState method on each request because registration
for control state is not carried over from request to request during a
postback event. It is recommended that registration occur in the Init event.

GridView calls this method in its OnInit:

protected internal override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Page != null)
{
if ((this.DataKeyNames.Length > 0) &&
!this.AutoGenerateColumns)
{
this.Page.RegisterRequiresViewStateEncryption();
}
this.Page.RegisterRequiresControlState(this);
}
}

Please note that it checks for "this.Page != null" first.

2) When adding a control to a ControlCollection, it will automatically
first remove it from its old parent.Controls (if its parent is not null),
and removing a control will Unload it first!

In previous code, when we first add the GridView to objForm.Controls,
because objForm is not added to Page.Controls yet, the "this.Page != null"
will be false for the GridView, thus not calling the
RegisterRequiresControlState.

So, what we are doing now is first adding the objForm to Page.Controls,
then add the remaining controls to objForm, this will ensure GridView's
ControlState is persisted.

As a side note, in ASP.NET 2.0, we have a new feature called MasterPage
which is exactly for the purpose of keeping a consistent look and feel for
the entire website.

Hope this helps. Please feel free to post here if anything is unclear.

Regards,
Walter Wang
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Walter, thanks for the reply. That fixed it. However, this brings up
another question. We currently use this base page for our 1.1 apps. We have
some groups in our company that are trying to use our base page compiled with
1.1 in their 2.0 web apps. This is the first issue we have ran into with
trying to use our 1.1 base code in a 2.0 app. If I go change our base page
to load the form into the page object before I load any controls into the
form collection, will this cause any problems with any of the 1.1 controls?

Also, in response to your side note, I wanted to use the Master pages but
unfortunately our base page is in a class library in a seperate assembly
rather than in the web application itself so there was no way to use the
master pages. At least this is what Microsoft told us. We distribute this
assembly throughout our company to let other development teams use in order
to have the corporate look and feel.

"Walter Wang [MSFT]" wrote:

> Hi,
> Thank you for your post.
> First, this problem can be fixed by using following BuildPage() function:
> private void BuildPage()
> {
> ArrayList al = new ArrayList();
> foreach(Control c in Controls)
> {
> al.Add(c);
> }
> Controls.Add(objForm);
> foreach(Control c in al)
> {
> objForm.Controls.Add(c);
> }
> }
> Following are detailed causes:
> 1) The root cause of this problem is GridView's PageIndex is stored using
> ASP.NET 2.0's new feature called "ControlState". See following MSDN for
> more info:
> http://msdn2.microsoft.com/en-us/li...atepersister.co
> ntrolstate.aspx
> A server control that use control state must call the
> RegisterRequiresControlState method on each request because registration
> for control state is not carried over from request to request during a
> postback event. It is recommended that registration occur in the Init event.
> GridView calls this method in its OnInit:
> protected internal override void OnInit(EventArgs e)
> {
> base.OnInit(e);
> if (this.Page != null)
> {
> if ((this.DataKeyNames.Length > 0) &&
> !this.AutoGenerateColumns)
> {
> this.Page.RegisterRequiresViewStateEncryption();
> }
> this.Page.RegisterRequiresControlState(this);
> }
> }
> Please note that it checks for "this.Page != null" first.
> 2) When adding a control to a ControlCollection, it will automatically
> first remove it from its old parent.Controls (if its parent is not null),
> and removing a control will Unload it first!
> In previous code, when we first add the GridView to objForm.Controls,
> because objForm is not added to Page.Controls yet, the "this.Page != null"
> will be false for the GridView, thus not calling the
> RegisterRequiresControlState.
> So, what we are doing now is first adding the objForm to Page.Controls,
> then add the remaining controls to objForm, this will ensure GridView's
> ControlState is persisted.
> As a side note, in ASP.NET 2.0, we have a new feature called MasterPage
> which is exactly for the purpose of keeping a consistent look and feel for
> the entire website.
> Hope this helps. Please feel free to post here if anything is unclear.
> Regards,
> Walter Wang
> Microsoft Online Community Support
> ==================================================
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> ==================================================
> This posting is provided "AS IS" with no warranties, and confers no rights.
>
Hi,

Thank you for your update and I'm glad that the suggestion worked.

Based on my research, adding an HtmlForm instance first is the preferred
way to mimic a normal ASP.NET page, since Control.Page property will use
parent to find the Page reference. If you add controls to HtmlForm first,
their Page reference are null and you don't know if they will check this
reference in OnInit or not. In a word, this "advanced" Page inheritance
technique is not officially supported so we have to test to see if it
really works.

As for the MasterPage issue, unfortunately it does need the *.master source
to be distributed.

Please feel free to post here if there's anything I can help.

Regards,
Walter Wang
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.