Wednesday, February 21, 2007

ASP.Net – Code to make a page read-only

Some times we may come across need to make all the ASP.Net controls on a page disabled, like for example after an order is processed we may want to make the order entry page read-only for future access. A quick way to do that is to loop through all the page controls, identify the type and disable them. A sample code on how I go about doing this…

In my App Helper class,

#region "Page Read-Only"

public static void DisablePageControls(Page curPage)

{

foreach (Control cntrl in curPage.Controls)

{

DisablePageControls(cntrl);

}

}

private static void DisablePageControls(Control myControl)

{

foreach (Control cntrl in myControl.Controls)

{

switch (cntrl.GetType().ToString())

{

case "System.Web.UI.WebControls.TextBox":

((TextBox)cntrl).Enabled = false;

break;

case "System.Web.UI.WebControls.Button":

((Button)cntrl).Enabled = false;

break;

case "System.Web.UI.WebControls.ImageButton":

((ImageButton)cntrl).Enabled = false;

break;

case "System.Web.UI.WebControls.DropDownList":

((DropDownList)cntrl).Enabled = false;

break;

case "System.Web.UI.WebControls.CheckBox":

((CheckBox)cntrl).Enabled = false;

break;

default:

break;

}

//Call for additional controls:

if (cntrl.HasControls())

DisablePageControls(cntrl);

}

}

#endregion "Page Read-Only"

Love coding!

4 comments:

Anonymous said...

have you used this "Page Read-Only" code That i got from web search.
can I get some idea or example to use this method with Asp.Net.


Thanks

Anwarul Haque
Revert at this email ID

anwarul.haque@metaoption.com

Anonymous said...

Thanks a lot. I used this code and its working perfectly for me.
May Allah bless you with emaan for sharing this great idea.

Anonymous said...

Instead of using swith statement, you could try this, which is far more elegant:

foreach (Control cntrl in myControl.Controls) {
if (cntrl is WebControl) {
(ctrl as WebControl).Enabled = false;
}
}

Anonymous said...

[Quote] Anonymous Anonymous said...

Instead of using swith statement, you could try this, which is far more elegant:

foreach (Control cntrl in myControl.Controls) {
if (cntrl is WebControl) {
(ctrl as WebControl).Enabled = false;
}
}
[/Quote]
If you did that then any tab controls you have would be disabled too. Using the switch allows you to choose only the controls that need disabled.