ASP.NET PopupControlExtender Problem - c#

I am trying to create a popup which will be used to select a month/year for a textbox. I have kind of got it working but however when I try and read from the textbox when I Submit the form it returns an empty string. However visually on the page I can see the result in there when I click the Done button which can be seen in the screenshot.
http://i27.tinypic.com/2eduttx.png - is a screenshot of the popup
I have wrapped the whole textbox/popup inside a Web User Control
Here is the code of the control
Code Behind
ASP Page
and then read from the Textbox on the button click event with the following
((TextBox)puymcStartDate.FindControl("txtDate")).Text
Any suggestions of how to fix the problem?

You may need to read the form posted value rather than the value from the view state. I have the following methods in my code to handle this.
The below code just grabs the values in the request headers (on post back) and sets/updates the controls. The problem is that when using the ASP.NET Ajax controls, it doesn't register an update on the control, so the viewstate isn't modified (I think). Anyways, this works for me.
protected void btnDone_Click(object sender, EventArgs e)
{
LoadPostBackData();
// do your other stuff
}
// loads the values posted to the page via form postback to the actual controls
private void LoadPostBackData()
{
LoadPostBackDataItem(this.txtYear);
LoadPostBackDataItem(this.txtDate);
// put other items here if needed
}
// loads the values posted to the page via form postback to the actual controls
private void LoadPostBackDataItem(TextBox control)
{
string controlId = control.ClientID.Replace("_", "$");
string postedValue = Request.Params[controlId];
if (!string.IsNullOrEmpty(postedValue))
{
control.Text = postedValue;
}
else
{
control.Text = null; // string.Empty;
}
}

Related

Event wont work with user control

I have a problem that I can't resolve on the server side of my project.
I'll explain:
I have a page named Global,this is ASP.NET page.
This page uses a UserControl named CateGories.
Now I have a button on this UC page,that when I press I want to invoke a function on the Global page that makes a connection with my DB.
I decided to use delegates(events)
This is the code.
Global page:
//here i add my function to the event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ShowCurrentTime.Text = DateTime.Now.ToString();
}
CateGories ClassCat = new CateGories();
ClassCat.MainDel += PopulateLinks;
}
//this is the function that the event will run
public void PopulateLinks(string CategoryName)
{....}
Code of the UC page (CateGories):
//delegation of the event
public delegate void Click(string ButtonName);
public event Click MainDel = null;
//function that invokes when I click a button
protected void News_Click(object sender, EventArgs e)
{
if (MainDel != null)
{
MainDel(News.Text);
}
}
Now everythig should work fine, but there is a problem, when the compiler gets to the
if(MainDel!=null)
...
It doesn't get in the function, there go MainDel is null.
I can't see the problem here, why after I insert function to MainDel, its gets null eventualy...
I'll be happy if someone can help
thanks.
Max.
I think I've encountered this problem before, when working with web applications the way I would a windows application.
The problem lies in that when the page gets reloaded, a new instance of your page class is created so any values from the last server interaction are lost.
MainDel is indeed null for what I can see.
You're creating one instance of CateGories on your Web Form and another one on your User Control. And once you check it for beeing null on the UC the reference is to the not initialized object.
One possible way to do that is creating and adding the User Control programatically to the page before PageLoad() and keeping a reference to it so you can access it's properties.
Another solution could be using Page.FindControl to find the UC and make the subscription to the event.
The method names above may be incorrect, it's been a long time without working with web forms.

Search button on Master page retrieves info late in the page lifecycle

In my current design approach I am running into a case where I'm having to perform an extra Database read and Databind on controls, only to overwrite them later on in the page lifecycle. The end result to the user is the same, but behind the scenes I'm doing two unnecessary and costly operations.
The search button is on the Master page. All the display controls (gridviews/tables/labels/etc) are on the content pages. The database call and databinding must be done in the Page_Init() method (most of the controls being used must be bound here).
When the user searches for an item, I save his search input in the session to persist it as being actively viewed across all the other content pages. So that when any content page is initialized, I check to see if they are actively viewing an item, and if so display his details.
// Master Page
protected void BtnSearch_OnClick(object sender, EventArgs e)
{
MySession.Current.ItemName = TxtItem.Text.Trim();
Server.Transfer("~/default.aspx");
}
// Content Page
protected void Page_Init(object sender, EventArgs e)
{
// If they're actively viewing an item, display its info
bool HasActiveItem = string.IsNullOrEmpty(MySession.Current.ItemName) ? false : true;
if (HasActiveItem)
{
// Makes one DB call to get all info;
// Binds all that info to GridViews/tables/labels on the page
BindAllDataControls(MySession.Current.ItemName);
// Display
DisplayItemDetails();
}
}
Here's the Issue: Say the user is currently viewing an Item = Boots. This value is saved in the session. Now the user searches for Item = Shirts and clicks the search button.
When the content page loads, he checks if there's anything in the session, there is but it's Item = Boots. It performs the unnecessary database/databind calls. Then, the BtnSearch click event triggers, we load the new Item = Shirts value into the session, and start the life cycle over. This lifecycle is good to go.
How can I get rid of that extra processing? Is the approach wrong?
I've thought about performing Page.IsPostback() and Page.IsCallback() logic during the content page initialization, but there are multiple other controls that cause postbacks and callbacks in the real web application. Therefore, I don't think I can get enough info from this to make the determination to skip or not. I've thought about wrapping the entire part of the page that contains all the GridViews/tables/labels/etc. in an ajax Callback, but I don't think that's a good approach. I've thought about sending an ajax call back to the server during the BtnSearch click that sets a flag. Then during load, we read that flag to skip or not, but there's no guarentee that that ajax call will process before the search BtnClick event.
Any ideas? Or should I just eat these extra calls and be done with it? There's got to be another way.
The most simple solution I see here is to make the check of search text change direct on PageInit and not on the button call.
// Master Page
protected void BtnSearch_OnClick(object sender, EventArgs e)
{
// remove that lines
// MySession.Current.ItemName = TxtItem.Text.Trim();
// Server.Transfer("~/default.aspx");
}
// Content Page
protected void Page_Init(object sender, EventArgs e)
{
// direct add here your variable on session
var vSearchText = TxtItem.Text.Trim();
if(!string.IsNullOrEmpty(vSearchText))
MySession.Current.ItemName = vSearchText ;
// ------------ rest of your code ---------------
// If they're actively viewing an item, display its info
bool HasActiveItem = string.IsNullOrEmpty(MySession.Current.ItemName) ? false : true;
if (HasActiveItem)
{
// Makes one DB call to get all info;
// Binds all that info to GridViews/tables/labels on the page
BindAllDataControls(MySession.Current.ItemName);
// Display
DisplayItemDetails();
}
}
Now to tell you the truth, the Server.Transfer is not good idea, what I do is that I use parameter in the URL, to include the search string from the input of the user, so when the user is add something for search I create the url as:
http://www.mydomain.com?q=test
and then I read the q and use it to fill the search box and make the search. This way you also have a SEO friendly search, the user can save his search and you avoid the server transfer that have other issues.

Disable Editing WebBrowser in C#

So I've been working on this project, and we have a WebBrowser object on the form. The purpose of the object is that it loads in HTML Forms into it to be viewed, at this current point in time though, you are able to edit the contents of the HTML form, which is not desired.
I want to simply display this HTML form of information to the user, but not allow them to alter the textboxes or checkboxes or anything of that nature on the form.
I tried using the Navigating event and set e.cancel = true;. This haulted the control from even loading the page. And if I set it to only execute e.cancel = true; after the form had loaded, I could still change text boxes and such on the form, as it only seemed to randomly called the Navigating event.
Does anyone know of a way to get a WebBrowser object to be read only?
Cheers!
You can apply contentEditable attribute to the Body tag of the document.
Document.Body.SetAttribute("contentEditable", false);
This will make your document readonly for user.
You could try accessing all form elements on the page and set the readonly attribute on the tag. Something like:
var inputs = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement element in inputs)
{
element.SetAttribute("readonly", "readonly");
}
You'd obviously have to repeat the process for all form elements (select etc.), but it should work.
I have been running into this issue as well. Thanks to steavy I have been able to come up with a solution :
Hook up to the DocumentCompleted event (you can do this in the designer) :
myWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_procedure_DocumentCompleted);
Then make it readonly in the event :
private void myWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
myWebBrowser.Document.Body.SetAttribute("contentEditable", "false");
}
I do this in the event when the document is fully loaded because I sometimes ran into a NullReferenceException, the body wasn't loaded yet and the line would throw.

Dynamic text box vanishing if another button or link button clicked

the code written below displays the text box for a certain condition.But when i click another unrelated button or link it dissapears.i need it to stay visible when i do other activities on the webpage
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox new_textbox = new TextBox();
if (DropDownList1.Text.Equals("OFF"))
{
new_textbox.ID = "txt" + 1;
PlaceHolder1.Controls.Add(new_textbox);
Label5.Visible = true;
new_textbox.Visible = true;
}
else
{
Label5.Visible = false;
}
}
This question has been asked on SO before:
Dynamically added controls in Asp.Net
You are only adding this control in a certain situation, specifically when DropDownList1.Text.Equals("OFF"). Could you instead have a static control that you just set visible in this case?
According to msdn's Add Controls to an ASP.NET Web Page Programmatically:
Controls are typically added to the page during the page's
initialization stage. For details about page stages, see ASP.NET Page
Life Cycle Overview.
The quote links to ASP.NET Page Life Cycle Overview.
You have to be careful about adding controls dynamically, see this msdn page about Dynamic Web Server Controls and View State.

How to access UserConrtorl's controls in this situation

I have an UpdatePanel.
and I have a PlaceHolder inside this UpdatePanel.
There is a number of UserControls. One of them will be loaded dynamically,
according to some selections.
Control mycontrol = this.Page.LoadControl("myusercontrol.ascx");
myplaceholder.Controls.Add(mycontrol);
after loading a specific UserControl, I wanted to get the text written in
a TextBox that is in the loaded UserControl from the Parent page.
TextBox mytextbox = (TextBox) Page.FindControl("myusercontrol")
.FindControl("mytextbox");
The problem was the text is always empty !
What am I missing ?
I appreciate your help.
You should load your UserControl overriding OnInit as mentioned before. And why were you looking entire page to find the UserControl? You can use PlaceHolder.Controls...
This how I got it work
protected override void OnInit(EventArgs e)
{
Control userControl = this.Page.LoadControl("WebUserControl.ascx");
testPlaceHolder.Controls.Add(userControl);
userControl.ID="id";
base.OnInit(e);
}
protected void testButton_Click(object sender, EventArgs e)
{
Control testUserControl = (Control)testPlaceHolder.Controls[0];
//Control testUserControl=(Control)testPlaceHolder.FindControl("id");
TextBox mytextbox = (TextBox)testUserControl.FindControl("testTextBox");
testButton.Text = mytextbox.Text;
}
When you say that the text is always empty, do mean the TextBox object is null or literally the .Text of the textbox is empty?
Remember that in web applications you have to post back to the server to refresh results and update controls among other things.
Try posting back to the server and seeing if that helps.
Have you considered adding a property to your user control to return the text?
eg:
public class YourControl : UserControl
{
public string Text
{
get
{
return this.TextBox1.Text;
}
}
}
Usually, User Controls are used for encapsulation - you wrap up all the details of controls, behaviour etc in a UC so other code doesn't have to deal with it.
By referring to controls within the UC directly - by name or ID - you're breaking the model. Can I suggest you don't do this, instead if you need to get information from the UC you add a property, event or method to it that the container can call.
That way if you need to change the UC - control names, types, styles, or additional logic is used later - you only need to change that property/event/method in the UC, not in the (for example) 100 places it might be used in the code.
If you could let us know why you need this information or more specific details about the example, perhaps we can suggest some code to implement this.
So, what should I do ?
Just get the posted values manually.
Request.Form[yourcondeol.UniqueID]
by debugging this you can see all the posted data.
Request.Form

Categories