how to access ascx custom control property from masterpage.master.cs - asp.net

I have this following property in my custom user control:
public string selectedtab
{
get
{
if (ViewState["AdminCurrentNavID"] != null)
{
return ViewState["AdminCurrentNavID"].ToString();
}
else {
isfirstload = true;
return null;
}
}
set { ViewState["AdminCurrentNavID"] = value; }
}
I am setting the value of it on my Page_Load() in ascx control. What i need to do is that after setting the value of this property I need to access it from masterpage.cs in code behind. you can see how currently I am trying to do in below code, but the issue is that I am not able to get the value i thing it is because the masterpage's Page_Load() rendering before the ascx control so I thats why I am getting null value, please help, thanks.
masterpage.cs:
usercontrols.mainmenu adminmenu = (usercontrols.mainmenu)LoadControl("~/mymenupath.ascx");
lbmsg.Text = adminmenu.selectedtab;

When you call LoadControl in your master page, you are actually creating a new instance of your user control, not accessing the one you have somewhere in your site.
When you declare the User Control in your page you should have given it an id. You could access the property with something like ((usercontrols.mainmenu)MyUserControlId).selectedtab

I found the solution by using Delegate, you can see in the link below.
http://webdeveloperpost.com/Articles/Return-value-from-user-control-in-ASP-NET-and-C-Sharp.aspx

Related

ASP.Net Custom Control - override onkeyup

I am having one problem which as simple as it may seem, gives me a lot of trouble. I have defined a custom control for a textbox in ASP.NET which has built-in the onkeyup attribute. My problem is that when using this control i want to override onkeyup, but it seems not to be working. My source code is the following:
this.Attributes.Add("onkeyup", "javascript:" + onKeyUp + ";"); // for the custom control
and when using it
< myControl:SpecialTextBox ID="txtValue" runat="server"/>
in code behind I did set
txtValue.Attributes.Add("onKeyUp", "DefaultValue();");
However, I keep on getting the onkeyup defined in the custom control instead of the more specific one.
Are there any solutions to this? Thank you very much!
Try to use txtValue.Attributes["onKeyUp"] = "DefaultValue();"; in codebehing of your page, this will override your custom control one.
You could add a property to your CustomControl:
public string OnClientKeyUp { get { /**/ } set { /**/ }
Set the default value in OnInit so you can override in a page later (e.g. Page_Load).
You can try to adding a property on your user contorl, something like this:
public string KeyUp
{
get
{
if (txtValue.Attributes["onKeyUp"] == null)
return string.Empty;
return txtValue.Attributes["onKeyUp"]
}
set
{
txtValue.Attributes["onKeyUp"] = value;
}
}
And on your server side asp.net tag you can call this property and set the value:
<myControl:SpecialTextBox ID="txtValue" runat="server" KeyUp="DefaultValue();" />

How to create a derived TextBox control?

I need to create a custom TextBox control that allows user input HTML tags. I added a new property called HtmlEnabled, default is false. If it is false, it will act exactly like the original TextBox; if it is set to true, it will call Server.HtmlEncode to encode the text. I never creat a custom control, can anyone tell me what do I need to do? What function I need to override? Thanks.
I created my TextBoxEx class as following: I still get the validation error when I set HtmlEnabled to true, can anybody tell me what is wrong?
namespace WebApplication1
{
[ToolboxData("<{0}:TextBoxEx runat=server></{0}:TextBoxEx")]
public class TextBoxEx : System.Web.UI.WebControls.TextBox
{
public bool HtmlEnabled
{
get
{
return (bool)ViewState["HtmlEnabled"];
}
set
{
ViewState["HtmlEnabled"] = value;
}
}
public TextBoxEx()
{
ViewState["HtmlEnabled"] = false;
}
public override string Text
{
get
{
if (HtmlEnabled)
return HttpUtility.HtmlEncode(base.Text);
else return base.Text;
}
set
{
if (HtmlEnabled)
base.Text = HttpUtility.HtmlDecode(value);
else base.Text = value;
}
}
}
}
Sounds like you could just inherit from the TextBox control and override the Text property. This article should get you started on how to go about doing it:
https://web.archive.org/web/20211020203142/https://www.4guysfromrolla.com/articles/100103-1.aspx
In order to allow the page to accept HTML tags, you need to disable request validation.
<%# Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="MyNamespace.TestPage" %>
This has nothing to do with the textbox control, the request validation checks all page input (query string parameters, cookies, headers, and form fields) to ensure that there are no potentially malicious scripts in the request. Be aware that by turning it off, you will need to validate that the input isn't harmful yourself.

Find control in usercontrol from a Page ASP.NET

I am loading a control to a page dynamically with LoadControl("src to file").
In the usercontrol i have a validator and some other controls that i would like to access from my page. I canät get it to work, null pointer exception.
Scenario is like this. I have a Edit.aspx page which loads the EditTemplate.ascx usercontroll. I would like to get information or find the controls in the EditTemplate from the Edit.aspx site.
I have tried exposing the controls and validators as properties but how do i access them from my Edit.aspx?
Example code:
Edit.aspx, the control is later added into a
Control control = LoadControl("src to ascx");
TemplatePlaceHolder.Controls.Add(control);
EditTemplate.ascx
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CompanyImageFile" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
CodeBehind
public partial class EditTemplate : System.Web.UI.UserControl, IEditTemplate {
public RequiredFieldValidator Validator {
get { return this.RequiredFieldValidator1; }
set { this.RequiredFieldValidator1 = value; }
}
From the Edit.aspx site i would like to check the validators isValid property. Isvalid is set in a Save method.
The save button that saves the template is located in edit.aspx, so the post in done from that page.
So the question is how to get a hold of the property from the usercontrol in the edit.aspx page, where and how should this be done?
Thanks again.
Easiest way is to have the user control define properties like:
public IValidator SomeValidator {
get { return this.cuvValidator; }
set { this.cuvValidator = value; }
}
public string Text {
get { return this.txtText.Text; }
set { this.txtText.Text = value; }
}
Which your edit page can use.
HTH.
You can always use recursive approach. Check the solution on Steve Smith's blog:
Recursive-FindControl.
As mentioned in previous answers, I would expose any validators you must access from the parent ASPX page as properties in the user control.
public RequiredFieldValidator ValidatorToCheck
{
get { return this.rfvMyField; }
}
Then, you can dynamically add your user control to some placeholder (being sure to assign an ID to the user control).
// In my example, this is occurring in the Page_Load event
Control control = LoadControl("~/Controls/EditTemplate.ascx");
control.ID = "ucEditTemplate";
pnlControlHolder.Controls.Add(control); // the placeholder in my example is a panel
When you want to access the IsValid property on the given validator (presumably in your save action) you can do so as follows (being sure to cast the control to the appropriate type and using the ID you originally assigned to the user control):
EditTemplate control = (EditTemplate)pnlControlHolder.FindControl("ucEditTemplate");
if (control.ValidatorToCheck.IsValid)
{
// Some action
}

set validatorcontrol.setfocusonerror="true" for all validator controls in asp.net website

We are about to release beta version of our website. Lately we have seen that developers have not set setfocusonerror on any of the validaor controls used.We have to set this property.
Now, one solution is to open every page and put this property in place. I am looking for some othe way like some configuration in web.config or some other quick solution.
I have usercontrols and pages. Page derive from base page.Please suggest.
Loops through all the page controls in the Page_Load event on your base page and do it. In this example, pass the Page to SetValidationControls
protected void SetValidationControls(Control control)
{
foreach(Control ctrl in control.Controls)
{
if(ctrl is System.Web.UI.WebControls.RequiredFieldValidator)
{
RequiredFieldValidator req = (RequiredFieldValidator)ctrl;
req.SetFocusOnError = true;
}
else if (ctrl is System.Web.UI.WebControls.RegularExpressionValidator)
{
RegularExpressionValidator reg = (RegularExpressionValidator)ctrl;
reg.SetFocusOnError = true;
}
else if (ctrl.Controls.Count > 0)
SetValidationControls(ctrl);
}
}
And so on.
You can create a set of validators that derive from the one's supplied by ASP.NET and use those. This allows you to have more control over it and make application wide changes, for instance, by using the themes & skins file.
For instance, when using the RequiredFieldValidator, you can override it and add a new themable property, like this:
public class CustomRequiredFieldValidator : RequiredFieldValidator
{
[ToolboxItem(true), Themeable(true), Category("Appearance")]
public bool FocusOnError
{
get { return this.SetFocusOnError; }
set { this.SetFocusOnError = value; }
}
}
And in the skin file you can define a default instance of your CustomRequiredFieldValidator.
<myOwn:CustomRequiredFieldValidator runat="server" FocusOnError="True" />
Now all CustomRequiredFieldValidator instances in your web application will have their SetFocusOnError attribute set.

Get MasterPage Hiddenfield Value From a User Class

Is there a way to get a value I am storing in a Master Page hidden field from a User Class which I created and placed in the App_Code folder of my ASP.Net 2.0 Application?
Some examples would preferably in VB.Net is highly appreciated.
Thanks.
To give further details, assume the following:
MasterPage.Master
MasterPage.Master.vb
MyPage.aspx
Mypage.aspx.vb
IN the app_code folder, add a new class, say TESTClass.
I have placed some logic in master page. MyPage.aspx uses the Masterpage.master as its master page. In the master page, the logic which I did stores a value into a hidden field.
in my TestClass, how do I access the master page hidden field?
Please take note that TestClass is NOT a user control but a user defined class, which contains some Business-Specific logic which is accessed by myPage.aspx.vb.
I tried ScarletGarden's suggestion but it did not seem to get the Masterpage Hiddenfield which I need to get the value.
Would something like this work?
((HiddenField)this.Page.Master.FindControl("[hidden control id]")).Text
You can get it by these :
hiddenControlValue = HttpContext.Current.Request["hiddenControlId"]
or you can pass your page to your method that belongs to your class under App_Config, and reach it as :
public static string GetHiddenValue(Page currentPage)
{
return currentPage.Request["hiddenValue"];
}
or you can get it over context :
public static string GetHiddenValue()
{
return HttpContext.Current.Request["hiddenValue"];
}
hope this helps.
EDIT: I re-read the question after answering, and realize my answer was probably not quite what you were after. :/
Jared's code might work, but you can also try the following.
In your MasterPage, make the HiddenField a public property, and store the content in the ViewState to make keep it during post backs.
Something like so:
public HiddenField theHiddenField
{
get
{
if (ViewState["HiddenField"] == null)
return null; //or something that makes you handle an unset ViewState
else
return ViewState["HiddenField"].ToString();
}
set
{
ViewState["HiddenField"] = value;
}
}
You then have to add the following to your ASCX-file:
<%# Reference Control="~/Masterpages/Communication.Master" %>
You then access it thusly.
Page mypage = (Page) this.Page; // Or instead of Page, use the page you're actually working with, like MyWebsite.Pages.PageWithUserControl
MasterPage mp = (MasterPage) mypage.Master;
HiddenField hf = mp.theHiddenField;
Sorry if the answer got a bit messy. This is, of course, how to do it in C#, if you want to use VB have a look at this link for the same idea.

Resources