Find all textbox control in a page - asp.net

i am trying to use http Module to disable textbox of each page. Here is my sample coding
public void context_OnPreRequestHandlerExecute(object sender, EventArgs args)
{
try
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
page.PreLoad += onPreLoad;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
public void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page.IsCrossPagePostBack)
{
DisableAllTextBoxes(page);
}
}
private static void DisableAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
var tb = c as Button;
if (tb != null)
{
tb.Enabled = false;
}
DisableAllTextBoxes(c);
}
}
This coding can work very well but when i use server.transer to another page. Button are not able to disable already.
For example webform1 transfer to webform2. Webform 1's button is able to disable but webform2 is not able to disable. Can anyone solve my problem?

Server.Transfer DOES NOT go through all http module pipline (thats why context_OnPreRequestHandlerExecute isn't executed for you )
you should try Server.TransferRequest or response.redirect or HttpContext.Current.RewritePath

Use LINQ to get all your textbox controls.
Don't use Server.Transfer()
Create an extension method on ControlCollection that returns an IEnumerable. That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
foreach (var t in textboxes)
{
t.Enabled = false;
}
...
public static class Extensions
{
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
}
Taken from this answer.

Related

crystal report viewer next page not working

I am using visual studio 2010 and crystal report 13.0
The report viewer displays the first page properly. But the next page button is not working. If i click on next page button then it shows loading message and stays there only.None of the report viewer controls are working.
please help me out
I found the solution.
Manually add the Page_Init() event and wire it up in the InitializeCompnent() with
this.Init += new System.EventHandler(this.Page_Init).
Move the contents of Page_Load to Page_Init().
Add if (!IsPostBack) condition in PageInIt.
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument crystalReportDocument = new ReportDocumment();
crystalReportDocument.SetDataSource(DataTableHere);
_reportViewer.ReportSource = crystalReportDocument;
Session["ReportDocument"] = crystalReportDocument;
}
else
{
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
_reportViewer.ReportSource = doc;
}
}
Instead of manually identifying the moment to bind, you could use the CrystalReportViewer AutoDataBind property in combination with the DataBinding event.
Autobind definition:
// Summary:
// Boolean. Gets or sets whether automatic data binding to a report source is
// used. If the value is set to True, the DataBind() method is called after
// OnInit() or Page_Init().
[Category("Data")]
[DefaultValue(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool AutoDataBind { get; set; }
You could use this property in the following manner:
In the ASPX:
<CR:CrystalReportViewer ID="_reportViewer" runat="server" AutoDataBind="true" OnDataBinding="_reportViewer_DataBinding" />
And in the ASPX.CS:
protected void _reportViewer_DataBinding(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportDocument crystalReportDocument = new ReportDocumment();
crystalReportDocument.SetDataSource(DataTableHere);
_reportViewer.ReportSource = crystalReportDocument;
Session["ReportDocument"] = crystalReportDocument;
}
else
{
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
_reportViewer.ReportSource = doc;
}
}
Done! Shift your Page load Event to Page Init Event.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int pageIndex =((CrystalDecisions.Shared.PageRequestContext)
CrystalReportViewer1.RequestContext).PageNumber;
//Bind Report with filter and datasource
string ControID = GetPostBackControlName(this);
//get and check Crystal Report Navigation button event after Bind Report
if (ControID == null)
{
((CrystalDecisions.Shared.PageRequestContext)
CrystalReportViewer1.RequestContext).PageNumber = pageIndex;
}
}
}
public string GetPostBackControlName(Page Page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = Page.FindControl(ctrlname);
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = Page.FindControl(ctrlStr);
}
else
{
c = Page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
if (control == null)
{
return null;
}
else
{
return control.ID;
}
}

value of private variable is not maintained after page load even in ASP.NET

I have two pages. first.aspx and second.aspx. In order to get all the control values from first.aspx, i added directive to second.aspx
<%# PreviousPageType VirtualPath="~/PR.aspx" %>
I have no problem to get all the previous page controls and set it to labels, but i have a big problem to save those values to a private variable, and reuse it after page load event is done. Here is code example. when i try to get the value from input in another method, it has nothing added. Why?
public partial class Second : System.Web.UI.Page
{
List<string> input = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null&&PreviousPage.IsCrossPagePostBack == true)
{
TextBox SourceTextBox11 (TextBox)Page.PreviousPage.FindControl("TextBox11");
if (SourceTextBox11 != null)
{
Label1.Text = SourceTextBox11.Text;
input.Add(SourceTextBox11.Text);
}
}
}
protected void SubmitBT_Click(object sender, EventArgs e)
{
//do sth with input list<string>
//input has nothing in it here.
}
}
The SubmitBT_Click-click event happens in a postback. But all variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your List, e.g. in the ViewState or Session.
public List<String> Input
{
get
{
if (Session["Input"] == null)
{
Session["Input"] = new List<String>();
}
return (List<String>)Session["Input"];
}
set { Session["Input"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application

ASP Is a foreach loop based on Button control on a Master page possible?

I'm trying to dynamically turn off all buttons on a webpage for a practicular group of users. So what I want to do is just set visble and enable = false.
So i'm kind of looking for something like this below.
foreach(Button idvButton on Master)
{
idvButton.Visible = false;
idvButton.Enable = false;
}
Any help is appreciated! Thanks!
How about this from your child page's code behind?
foreach(var btn in Master.Page.Form.Controls.OfType<Button>())
{
btn.Visible = false;
btn.Enabled = false;
}
This disables all buttons found throughout entire MasterPage.
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
disableButtons(ctrl);
}
}
void disableButtons(Control ctrl)
{
foreach (Control ctrl2 in ctrl.Controls)
{
if (ctrl2.GetType() == typeof(Button))
{
((Button)ctrl2).Enabled = false;
((Button)ctrl2).Visible = false;
}
}
}
}
Here is the answer: Had to combine both previous posts.
foreach (var btn in this.Page.Form.Controls.OfType<RadButton>())
{
btn.Visible = false;
btn.Enabled = false;
}

how to use updatepanel with AsyncRefresh event

I developing an asp.net web application.In that application i am using asyncRefresh event
for continuously updating the value.If i am using updatepanel the asyncRefresh event won't get the focus.Without updatepanel evet getting the focus.I want to use asynRefresh event with updatepanel.Any one Please help for this problem.
Thanks&Regards
Lijo Thomas
protected void Page_Load(object sender, EventArgs e)
{
object et = Request.Form["__EVENTTARGET"] as object;
if (et != null)
{
Control c = Page.FindControl(et.ToString());
if (c != null)
{
ScriptManager.GetCurrent(this).SetFocus(GetUniqueIdSmart(c));
}
}
}
protected static string GetUniqueIdSmart(Control control)
{
string id = control.UniqueID.Replace('$', '_');
string controlIDSuffix = "";
RadioButtonList rbl = control as RadioButtonList;
if (rbl != null)
{
controlIDSuffix = "_0";
int t = 0;
foreach (ListItem li in rbl.Items)
{
if (li.Selected)
{
controlIDSuffix = "_" + t.ToString();
break;
}
t++;
}
}
else if (control is CheckBoxList)
{
controlIDSuffix = "_0";
}
id += controlIDSuffix;
return id;
}

Saving State Dynamic UserControls...Help!

I have page with a LinkButton on it that when clicked, I'd like to add a Usercontrol to the page. I need to be able to add/remove as many controls as the user would like. The Usercontrol consists of three dropdownlists. The first dropdownlist has it's auotpostback property set to true and hooks up the OnSelectedIndexChanged event that when fired will load the remaining two dropdownlists with the appropriate values.
My problem is that no matter where I put the code in the host page, the usercontrol is not being loaded properly. I know I have to recreate the usercontrols on every postback and I've created a method that is being executed in the hosting pages OnPreInit method. I'm still getting the following error:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
Here is my code:
Thank you!!!!
bool createAgain = false;
IList<FilterOptionsCollectionView> OptionControls
{
get
{
if (SessionManager.Current["controls"] != null)
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
else
SessionManager.Current["controls"] = new List<FilterOptionsCollectionView>();
return (IList<FilterOptionsCollectionView>)SessionManager.Current["controls"];
}
set
{
SessionManager.Current["controls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Master.Page.Title = Title;
LoadViewControls(Master.MainContent, Master.SideBar, Master.ToolBarContainer);
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if ((control != null && control.ClientID ==
(lbAddAndCondtion.ClientID) || createAgain))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
protected void AddAndConditionClicked(object o, EventArgs e)
{
var control = LoadControl("~/Views/FilterOptionsCollectionView.ascx");
OptionControls.Add((FilterOptionsCollectionView)control);
control.ID = "options" + OptionControls.Count.ToString();
phConditions.Controls.Add(control);
}
public event EventHandler<Insight.Presenters.PageViewArg> OnLoadData;
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
phConditions.Controls.Add(c);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Here is the usercontrol's code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FilterOptionsCollectionView.ascx.cs" Inherits="Insight.Website.Views.FilterOptionsCollectionView" %>
namespace Insight.Website.Views
{
[ViewStateModeById]
public partial class FilterOptionsCollectionView : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
LoadColumns();
ddlColumns.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ColumnsSelectedIndexChanged);
base.OnInit(e);
}
protected void ColumnsSelectedIndexChanged(object o, EventArgs e)
{
LoadCriteria();
}
public void LoadColumns()
{
ddlColumns.DataSource = User.GetItemSearchProperties();
ddlColumns.DataTextField = "SearchColumn";
ddlColumns.DataValueField = "CriteriaSearchControlType";
ddlColumns.DataBind();
LoadCriteria();
}
private void LoadCriteria()
{
var controlType = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].CriteriaSearchControlType;
var ops = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].ValidOperators;
ddlOperators.DataSource = ops;
ddlOperators.DataTextField = "key";
ddlOperators.DataValueField = "value";
ddlOperators.DataBind();
switch (controlType)
{
case ResourceStrings.ViewFilter_ControlTypes_DDL:
criteriaDDL.Visible = true;
criteriaText.Visible = false;
var crit = User.GetItemSearchProperties()[ddlColumns.SelectedIndex].SearchCriteria;
ddlCriteria.DataSource = crit;
ddlCriteria.DataBind();
break;
case ResourceStrings.ViewFilter_ControlTypes_Text:
criteriaDDL.Visible = false;
criteriaText.Visible = true;
break;
}
}
public event EventHandler OnColumnChanged;
public ISearchCriterion FilterOptionsValues { get; set; }
}
}
I figured it out. Here is my solution:
I modified the GetPostBackControl to look for not only the linkbutton that inserts the user control, but for controls that contain the id of child controls of the inserted user control(as to capture the OnSelectedIndexChanged that gets fired from inside my user control).
protected Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
//if it contains options then it's a control inside my usercontrol
if (ctrlname.Split('$')[2].Contains("options"))
{
var c = new Control();
c.ID = ctrlname;
return c;
}
else
{
control = FindControlRecursive(page, ctrlname.Split('$')[2]);
}
}
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form)
{
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.CheckBox ||
c is System.Web.UI.WebControls.CheckBoxList)
{
control = c;
break;
}
}
}
return control;
}
Then I modify the OnPreInit event to look for controls with an id of the linkbutton or an id that contains "options" :
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
System.Web.UI.MasterPage m = Master;
Control control = GetPostBackControl(this);
if (control != null)
{
if ((control.ClientID == (lbAddAndCondtion.ClientID) || createAgain) || control.ID.Contains("options"))
{
createAgain = true;
CreateUserControl(control.ID);
}
}
}
The critical fix was in the CreateUserControl method. In my original code I was trying to directly load the user control from my generic list that was stored in Session. I changed that to actually create a new instance of the user control, assign that new instance an id that matches the one stored in Session, and then add it to the placeholder:
protected void CreateUserControl(string controlID)
{
try
{
if (createAgain && phConditions != null)
{
if (OptionControls.Count > 0)
{
phConditions.Controls.Clear();
foreach (var c in OptionControls)
{
FilterOptionsCollectionView foc = new FilterOptionsCollectionView();
foc = Page.LoadControl("~/Views/FilterOptionsCollectionView.ascx") as FilterOptionsCollectionView;
foc.ID = c.ID;
phConditions.Controls.Add(foc);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The only thing I changed in the user control was moving the method that loads my drop down lists's and wiring up the OnSelectedIndexChanged event into the OnInit event. Now I can dynamically load as many instances of the user control I want and all of the event's inside the user control fire correctly and state is persisted across postbacks!!
Hope this helps someone else!!

Resources