I have this piece of code:-
What I want is that in button click i want put some value in user control.
I get Object reference error.
if (Page.FindControl("pr1") is Control)
{
Control previewControl = Page.FindControl("pr1");
Label titleLabelPreview = (Label)previewControl.FindControl("titleLabel");
titleLabelPreview.Text = emptxt.Text;
However, if i used it through master page it can not intialized
but if i use parent page it work properly.
But here, one more problem persisted, suppose the scenario
use a tab container
where is 3 tab panel
in first panel i used a button
when i click that button i want to change the tab panel view
means 2nd panel
but without refresh the page. and one important thing i don't want to use update panel on tab container. I do not wish to use ajax or javascript. any insight on this.
Also, would be really great if someone gives me a deep idea how to resolve object reference errors.
I read a few blogs like:_
http://www.mikesdotnetting.com/Article/62/Object-reference-not-set-to-an-instance-of-an-object-and-INamingContainer
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.passwordrecovery.usernametemplate.aspx
however, was not fully satisfied.
Related
I have an UpdatePanel in the page.
Inside this UpdatePanel, I have a control which has a button.
Is it possible to Manually add a postback trigger for this button (which is inside the user control) in the code behind?
Here's the sample code
//Page
<UpdatePanel>
<uc1:UserControl />
</UpdatePanel>
//UserControl
<textbox></textbox>
<asp:button></asp:Button>
As I understand, you want to register the button in your user control as a PostbackTrigger of an UpdatePanel in your ASPX page which contains your user control.
I have managed to write a simple web application that replicates this scenario and without further information I cannot see where you're going wrong or what the error that you're getting is, if any. It would help if you expanded on your original question e.g. by providing relevant snippets of your code. I'll try my best...
From within the user control you can register the button as a post back trigger of the update panel with the following code:
public void RegisterPostbackTrigger(UpdatePanel updatePanel)
{
PostBackTrigger buttonTrigger = new PostBackTrigger();
buttonTrigger.ControlID = TestButton.ClientID;
updatePanel.Triggers.Add(buttonTrigger);
}
You will then have to call the RegisterPostbackTrigger from within you page's code behind passing in you UpdatePanel's reference as an argument. MyControl refers to the UserControl
MyControl.RegisterPostbackTrigger(MainUpdatePanel);
An alternative way of doing this, which may be relevant to your particular issue is to access the ScriptManager directly and use its RegisterPostBackControl method passing in your button as the parameter. Here's the a link!
Can't really help you anymore without more information!
Good luck!
I have a Search.aspx page which calls UCSearch control. UCSearch control does everything like getting what is being searched and what should be displayed, etc. I am trying to give the title to the page. As i dont have any info to write the code in the aspx page, i am thinking to write it in the control. But it is not displaying me when i tried using Page.Title in control. What am i doing wrong?? This is in Asp.net and C#.
Page.Title = "Search Results for Newark, NY";
Thanks in advance!!
Does not:
this.Page.Title = "My beautiful title";
work?
You should be able to get to the ASPX using the Parent property of the control. Cast that property to a Page (it's a WebControl or something similarly generic), then set its Title property. If you have a hierarchy of master pages or are nesting this control in other controls, you may need to traverse the Parent hierarchy for a few more levels.
You could also fire an event from your user control, passing the Title that you would like to display. You could then handle this event on the page, and set the title.
This does require a small amount of code in your aspx page, however, at least now the user control does not care where the title goes, the parent of the control can worry about it. If ever you want to change where this title goes, or even put it in multiple places, you don't have to change the user control. Let me know if you want a sample, I'll add it.
If you don't like that idea, then cederlof's answer will work, I just tested it.
protected void helloBtn_Click(object sender, EventArgs e)
{
this.Page.Title = "hello from control";
}
** You can use naming container to find the parent control of the current control. Through this way you can move through the page hierarchy.
Quickwatch will help you a lot in figuring out the things and building the statement for quick casting. Do some more research on naming container.
var container = userControl.NamingContainer;
if(container is Page)
{
Page p = container as Page;
p.Title = "Your Title";
}
**
Above is not the exact solution, but can help you it you can usercontrol directly on the page. Unless you need to iterate through the page controls. This was just for an quick help.
The Scenario: I have an asp.net website where I show a div popup on page load for taking a few user details. When a user inputs the details, or closes the popup, I set up a flag cookie so that the popup is not displayed again for the user. The div is in the MasterPage so that it is displayed no matter on which page a user lands first time. The div contains an UpdatePanel which has all the controls required for taking the details. This whole functionality is working fine.
The Problem: Now this div popup is not showing(by setting display:none) on subsequent postbacks(which I want), but the html markup is still loading with the page unnecessarily adding to the page size. What I would idealy want to do is: Check if flag cookie is set. If no, show the popup, else remove the popup's markup from the page.
Now since the div is not a server control, I cannot possibly remove it and the all the controls inside it. So, I thought of removing the UpdatePanel from the page:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["flag"] != null)
{
if (Page.Controls.Contains(updpnl_contact))
{
Page.Controls.Remove(updpnl_contact);
updpnl_contact.Dispose();
}
}
}
But I guess this tends to work with dynamically added controls only, and since the control is added at Design Time, it is not being removed.
Is there any way I can achieve this?
If you add a runat="server" attribute to your <div> element, it will be available in the code-behind. You'll need an id on it as well. Then you can just toggle the Visible property. If this property is false, the control won't be rendered to the client (i.e. no HTML markup).
What you're trying to do is not at all the usual workflow. I tend to think that it will not work as it would mess up control tree, maybe even corrupt the viewstate and so on.
As a possible solution, you can put it's visibility to hidden in the code behind. This, in the contrary to the usual 'gut feeling', doesn't work like the css propery 'display:none' for example - instead the control will not even be rendered into the page when it's not visible. This may be the workaround for you.
Happy coding.
A more efficient approach would be to create the panel as a UserControl and load it dynamically in codebehind when it's needed, then add it to your page. E.g, in code:
MyPopupControl popup = (MyPopupControl)Page.LoadControl("/path/to/usercontrol.ascx");
PopupPanel.Controls.Add(popup);
Where PopupPanel is an empty <asp:Panel>. Then, not even the markup will need to be loaded/processed except when its needed.
There is no reason that all the code you use to display and process this panel couldn't also be in the usercontrol, isolating it from the master page.
Can you build the panel dynamically, based on the cookie setting?
So I have a masterpage with a login that is in an update panel. I have a child page that has a literal control that should update when the login updates. What it doesn't do is reload the method I use to generate the content for that literal when it posts back. I tried to call the method on the child page from the master page once you click log in, but I get an error that the literal control cannot be found (because it exists on the child page not the master page). How would I reference that control in the masterpage to pass it to my method?
The article below shows how the control tree works with MasterPages and how to reference different controls at different levels of the control tree.
ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps
So the scenario is that you have an update panel on the child page that when triggered doesn't update/refresh your lets say, label which is in your header on your master page.
What you do is, in the code behind of your master page create a function that changes the value of the label.
Include an update panel on the master page for the label, which is triggered by the textchanged event etc.
Now, in your child page code behind or your let say, button click event, call upon the function that exists in the master page and send the needed value in the parenthesis.
C#:
((MyMaster)this.Page.Master).ShowMessage(text);
VB.NET:
DirectCast(Me.Page.Master, MyMaster).ShowMessage(text)
This should update the label with the correct value whilst triggering the update panel on the master page and thus refreshing your label as well.
I'm about to try this now for myself, wish me luck. :D
I have a menu usercontrol called LeftMenu that has a bulletedlist of linkitems. It's on the ascx page as such:
<asp:BulletedList ID="PublisherList" DisplayMode="LinkButton" OnClick="PublisherList_Click" cssClass="Menu" runat="server"></asp:BulletedList>
I databind the list in the page_load under if(!isPostBack)
I'm having an issue on a page that loads the control. When the page first loads, the event handler fires. However, when the page posts back it no longer fires and in IE8, when I'm debugging, I get "Microsoft JScript runtime error: Object expected" in Visual Studio pointing at "__doPostBack('LeftMenu$PublisherList','0')." In FF I don't get the error, but nothing happens. I'm not loading the control dynamically, it's loaded on the aspx page using:
<%# Register TagPrefix="Standards" TagName="LeftMenu" Src="LeftMenu.ascx" %>
<Standards:LeftMenu ID="LeftMenu" runat="server"/>
Any ideas of where I'm losing the event handler?
I just realized this is happening on another user control I have as well. A text box and a button and I'm using the default button to make sure pressing the enter key uses that button. .Net converts that in the html to:
<div id="SearchBarInclude_SearchBar" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'SearchBarInclude_QuickSearchButton')">
so as soon as i enter a key in the box I get a javascript error at the line saying "object expected." It seems like the two issues are related.
Edit Again: I think I need to clarify. It's not that I'm clicking on the menu item and it can't find the selected item on postback. I have this search page with the left navigation on it and then the main content of the page is something that causes a postback. Everything is fine with this postback. Once that page has been posted back, now if I click on the bulleted list in the left navigation I get a javascript error and it fails. The page_init for the LeftMenu control is never called.
It sounds like you might be losing the click because you are not DataBinding the list on PostBack. Therefore, the post back is trying to refer to a control (a specific bulleted list item) that does not exist.
You should try binding the list again on PostBack just to see if that fixes your issue. BUT, what should REALLY happen is that the LeftMenu and the BulletedList should store their information into ViewState so that you can ensure that the data that was shown to the user on their initial page load is the same data that the PostBack is processing and working with.
If you have EnableViewState=true for your UserControl and all controls within it, everything should work fine. With ViewState enabled, ASP will reinflate your controls from ViewState after Init has fired. This means that the postback event arg (which points to an index in your control list) will still find the control in that list position. Otherwise the list is empty on postback.
However, ViewState is the work of the devil and was designed simply to foster the illusion that you are working in a stateful environment. It is okay to use it for small amounts of data but typically not advisable for templated controls like repeaters and lists because you have no idea how much data is going to be created in ViewState.
If you are dealing with static, or relatively static data, store it in the application cache and rebind your lists in Page.Init every time (note that it has to be in Init because post-init is when ASP rebinds from ViewState; if you get in there first, your data will be used instead).
If you are dealing with volatile data, you have a problem because the data you rebind must be exactly the same as the original page request, otherwise the postback events will be firing against the wrong rows. In that case you need to either store your initial data in Session or you simply store the list of rows ids (in a hidden variable or Session) and you recreate the data to bind against from the ids each time.
An even better solution is to not use postback events at all. Try to turn all your events into GETs that have an ID on the query string. You can still create the list using binding the first time through the page (as you are currently doing), and you can even GET the same page with a new ID.
If you need to keep state on the same page but need to respond to the user changing a radio button selection (or something else), think about using Ajax calls to update the screen. You also do that with an ID that you pass to the Ajax call.
In general, the more you move from using stateful ASP, the lighter and more responsive your pages will become. You will also be in a better position to move to stateless MVC if necessary. You will also save lots of time lost to debugging obscure problems because ViewState is not available when you need it to be.
The best analysis of ViewState I've read is in the link below. If you fully understand how it works, you can continue to use it without necessarily incurring the costs.
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx
It's possible that this might be javascript related, and that a script that is loading earlier in the page is throwing an error and causing the page to not be loaded properly.
Are your usercontrols loading any javascript onto the page? Can you check for javascript errors on the initial load of the page?
I moved the code into an existing project we have and for some strange reason, I stopped getting the javascript errors and instead got:
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
I haven't quite figured out where I'm supposed to put the register event validation with a user control, but in the mean time I just set enableeventvalidation=false and it seems to work now.
It looks like the doPostBack function is missing since its arguments are literals so they couldn't be the cause. Is that one of your own functions or did you mean to call the ASP __doPostBack function?
Have a look at the Firefox error console or allow script debugging in IE and see exactly what object can't be found. Even better, download Firebug and debug it.
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.