How to use Partial Caching with dynamically created controls? - asp.net

I have a control declared with PartialCaching attribute, like this:
[PartialCaching(60 * 60 * 12)]
public class MyControl : Control {
// control contents ...
}
but I create it in code, using new keyword. The problem is that if the control is in cache I must not create the control again the next time, but I need to add the control to the page hierarchy, otherwise nothing is going to be rendered. What I need in pseudo-code is something like this:
if (myControlIsCached) {
var ctl = ???; // something that represents the cached control
// e.g. could be: new LiteralControl( myControlCachedData )
this.Controls.Add( ctl );
}
else {
var ctl = new MyControl();
// setup control ...
this.Controls.Add( ctl );
}
What is the correct way of doing it?
Thanks people.

I believe you are looking to do something like this:
Control possiblyCachedControl = LoadControl("path to control");
MyControlType control = null;
if (possiblyCachedControl is MyControlType)
{
//control wasn't cached
control = possiblyCachedControl as MyControlType;
}
else if (possiblyCachedControl is PartialCachingControl && ((PartialCachingControl)possiblyCachedControl).CachedControl != null)
{
//control was cached
control = (MyControlType)((PartialCachingControl)possiblyCachedControl).CachedControl;
}
if (control != null)
{
//use the control
}

Related

dynamically created controls within a usercontrol is not recognized

In the ascx.cs file I'm dynamically generating buttons. In .aspx file I add the control to the form. The control itself renders well, but when the buttons are clicked I get this error
An error has occurred because a control with id 'ctl03' could not be
located or a different control is assigned to the same ID after
postback.
DestopControl.ascx.cs
public partial class DesktopControl : PlaceHolder
{
public void Build()
{
for (int i = 0; i < 10; i++)
{
Button button = new Button()
{
Width = 50,
Height = 50,
ID = string.Format("button{0}", i),
Text = i.ToString()
};
button.Click+=new EventHandler(button_Click);
}
}
}
Default.aspx.cs
DesktopControl desktop = new DesktopControl();
desktop.Build();
MainContent.Controls.Add(desktop);
After reading the comments (little hard to read the code-part of the comments) it appears that yes, you are generating your controls inside an if(!isPostBack){}; well, looks like it's in the else part of that if statement.
You have to generate your controls every time the page posts back, as the page_load gets fired before your button click. So once the controls have been re-created the code will continue on to your button click handler, where the controls should be available to handle.
Essentially, take ReloadUI(Session["ui"]); OUT of the if(!isPostBack){}else{} statement. Put it after your if statement.
Like this:
if (!isPostBack){
// my first load code
}else{
// my postback code
}
// load all my dynamic controls here
ReloadUI(Session["ui"]);
Found a solution:
Every time there is a new UI I call this ClearScreen() which does the trick.
The error on 'ctl03' was a menu control which was generating it's own ID and somehow wasn't available on postback. I assigned an ID to it. But I guess all the issue went away with this ClearScreen() method.
private void ClearScreen()
{
try
{
List<Control> controls = new List<Control>();
foreach (Control control in MainContent.Controls)
{
controls.Add(control);
}
for (int i = 0; i < controls.Count; i++)
{
if (!(controls[i].GetType() == typeof(LiteralControl) || controls[i].GetType() == typeof(ScriptManager)))
{
MainContent.Controls.Remove(controls[i]);
}
}
}
catch (Exception ex)
{
}
}

How to access control from parent aspx from its child ascx

I try to access the MainContentBlock control from the aspx, but unable to do so.
In the aspx file I have registered both controls:
<uc3:ContentBlock ID="MainContentBlock" runat="server" DynamicParameter="id" DefaultContentID="3951" /></uc3>
<uc3:childshow ID="Childshow" runat="server"/></uc3>
In the code behind for child.ascx
If Me.Parent.Page.FindControl("MainContentBlock") IsNot Nothing AndAlso Me.MainContentBlock.Item.Id = 4357 Then
...
But the error says BC30456: 'MainContentBlock' is not a member of 'child'.
It's almost like the ".parent" part did not work.
However, If I try the following:
If Me.Parent.MainContentBlock IsNot Nothing AndAlso Me.MainContentBlock.Item.Id = 4357 Then
...
It will bring up the error "BC30456: 'MainContentBlock' is not a member of 'System.Web.UI.Control'.
and seems it at least recognized the .parent part again.
confused... please help, thanks.
It's because you're trying to reference MainContentBlock as a property of the child control. When you use Me.MainContentBlock, Me refers to the child control.
You just need to use FindControl, and properly reference the found control:
Dim myBlock As ContentBlock = TryCast(Me.Parent.FindControl("MainContentBlock"), ContentBlock)
If myBlock IsNot Nothing Then
'do things with myBlock
End If
Depending on where the control is located on the page, you may need to find it recursively, but in a simple situation you would just do this:
var pnl = Page.FindControl("MainContentBlock") as Panel; //or whatever it is
if (pnl != null)
{
//your code here
}
Here's a recursive method if you need it:
public Control FindControlRecursive(string controlID, Control parentCtrl)
{
foreach (Control ctrl in parentCtrl.Controls)
{
if (ctrl.ID == controlID)
return ctrl;
FindControlRecursive(controlID, ctrl);
}
return null;
}
And you would call it like this:
var pnl ((PageName)Page).FindControlRecursive("MainContentBlock") as Panel;
FindControl works but the pain is that what you're looking for can be higher then just at parent level. Here is a handy method I use:
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
foreach (Control ctl in root.Controls)
{
Control foundCtl = FindControlRecursive(ctl, id);
if (foundCtl != null)
return foundCtl;
}
return null;
}

Datalist paging in asp.net?

In asp.net Web application, i write code for datalist paging like this :
PagDat = new PagedDataSource();
PagDat.AllowPaging = true;
PagDat.PageSize = 10;
PagDat.CurrentPageIndex = **currentpage**;
PagDat.DataSource = ds.Tables[0].DefaultView;
dtlstMagazine.DataSource = PagDat;
dtlstMagazine.DataBind();
In this "currentpage" is a integer varaible which i declared as a static. I think it could be conflict when more user access this page am i right?
Yes your are right.
You should Save your PageDataSouce page index in State Management
object. using static variable is not a good approach in web
application for such page level operations.
Create CurrentPage property:
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int) o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
Check following link for more information:
Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

Better way to find control in ASP.NET

I have a complex asp.net form,having even 50 to 60 fields in one form like there is Multiview, inside MultiView I have a GridView, and inside GridView I have several CheckBoxes.
Currently I am using chaining of the FindControl() method and retrieving the child ID.
Now, my question is that is there any other way/solution to find the nested control in ASP.NET.
If you're looking for a specific type of control you could use a recursive loop like this one -
http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx
Here's an example I made that returns all controls of the given type
/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control
{
private readonly List<T> _foundControls = new List<T>();
public IEnumerable<T> FoundControls
{
get { return _foundControls; }
}
public void FindChildControlsRecursive(Control control)
{
foreach (Control childControl in control.Controls)
{
if (childControl.GetType() == typeof(T))
{
_foundControls.Add((T)childControl);
}
else
{
FindChildControlsRecursive(childControl);
}
}
}
}
Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:
public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
where T : Control
{
foreach (Control child in parent.Controls)
{
if (child is T)
{
yield return (T)child;
}
else if (child.Controls.Count > 0)
{
foreach (T grandChild in child.FindControlsOfType<T>())
{
yield return grandChild;
}
}
}
}
All the highlighted solutions are using recursion (which is performance costly). Here is cleaner way without recursion:
public T GetControlByType<T>(Control root, Func<T, bool> predicate = null) where T : Control
{
if (root == null) {
throw new ArgumentNullException("root");
}
var stack = new Stack<Control>(new Control[] { root });
while (stack.Count > 0) {
var control = stack.Pop();
T match = control as T;
if (match != null && (predicate == null || predicate(match))) {
return match;
}
foreach (Control childControl in control.Controls) {
stack.Push(childControl);
}
}
return default(T);
}
FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.
Theres a reason that ASP.Net does not look into your nested controls recursively by default:
Performance
Avoiding errors
Reusability
Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.
Action Management On Controls
Create below class in base class.
Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database:
Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx:
in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS:
Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
Recursively find all controls matching the specified predicate (do not include root Control):
public static IEnumerable<Control> FindControlsRecursive(this Control control, Func<Control, bool> predicate)
{
var results = new List<Control>();
foreach (Control child in control.Controls)
{
if (predicate(child))
{
results.Add(child);
}
results.AddRange(child.FindControlsRecursive(predicate));
}
return results;
}
Usage:
myControl.FindControlsRecursive(c => c.ID == "findThisID");
I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().
protected void Page_Load(object sender, EventArgs e)
{
this.BuildControlDics();
}
private void BuildControlDics()
{
_Divs = new Dictionary<MyEnum, HtmlContainerControl>();
_Divs.Add(MyEnum.One, this.divOne);
_Divs.Add(MyEnum.Two, this.divTwo);
_Divs.Add(MyEnum.Three, this.divThree);
}
And before I get down-thumbs for not answering the OP's question...
Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET?
A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.
https://blog.codinghorror.com/recursive-pagefindcontrol/
Page.FindControl("DataList1:_ctl0:TextBox3");
OR
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;
}
The following example defines a Button1_Click event handler. When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page. If the control is found, its parent is determined using the Parent property and the parent control's ID is written to the page. If TextBox2 is not found, "Control Not Found" is written to the page.
private void Button1_Click(object sender, EventArgs MyEventArgs)
{
// Find control on page.
Control myControl1 = FindControl("TextBox2");
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}
}

Cannot Access the Controls inside an UpdatePanel

What I am trying to do is accessing Page Controls at Page_Load, and make a database query, and make controls visible or not visible.
Here is the Code:
foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) {
try {
if (thiscontrol.ID.Contains("TextBox") || thiscontrol.ID.Contains("Label")) {
string dummy = thiscontrol.ID;
bool IsValid = db.Roles.Any(a => a.controlName == dummy);
if (IsValid == false)
thiscontrol.Visible = false;
}
else if (thiscontrol.ID.Contains("UpdatePanel")) {
foreach (Control UPcontrols in ((UpdatePanel)thiscontrol).ContentTemplateContainer.Controls) {
if (UPcontrols.ID.Contains("TextBox") || UPcontrols.ID.Contains("DropDownList")) {
bool UPIsValid = db.Roles.Any(a => a.controlName == UPcontrols.ID);
if (UPIsValid == false)
UPcontrols.Visible = false;
}
}
}
}
catch { }
}
My Problem is with the UPcontrols! It should retrieve the controls within the UpdatePanel, but the thing is it doesn't do its job, except in the debug mode!
When I add a breakpoint, everything is OK, but when I run the web application, it doesn't find any components within the UpdatePanel...
Try this one:
ControlCollection cbb = updatepanel1.Controls;
ControlCollection cb = cbb[0].Controls;
initialize_Controls(cb);
public void initialize_Controls(ControlCollection objcontrls)
{
foreach (Control tb in objcontrls) {
if (tb is TextBox)
((TextBox)tb).Text = "";
if (tb is Panel) {
ControlCollection cbcll = tb.Controls;
foreach (Control tbb in cbcll) {
if (tbb is TextBox)
((TextBox)tbb).Text = "";
}
}
}
}
First find controls from updatepanel i.e ContentTemplate, then find controls from contentTemplate which contain all controls in it.
This seems like a very bizarre design. That is, using control IDs for such purposes is rather unusual.
Nevertheless, you need a recursive method here to do a deep walk of every control on the page. Your method will not work if the UpdatePanel is contained within another control.
Have a check on this article
http://www.codeproject.com/Articles/24178/The-magical-effects-of-the-UpdatePanel-control-in

Resources