Hey
i've made a simpel little web part with a few text boxes, a calendar and some buttons, but when i change the date, the whole web part reloads and everything written in the textboxes is lost... ![]()
HOW CAN I PREVENT THIS
im using VS 2005 C# and sharepoint 2007, and have tried using ViewState, but it doesn't work ><
pleeease help
mads

How do i get my web part to remember input when it reloads ???
lcj
hi
I tried the if(page.ispostback) but our problem didn't go away...
the problem is that the whole web part reloads, every time we push a button or choose a date in the calendar. It re-creates all the controls
System.Web.UI.WebControls.TextBox Titel = new TextBox();
...
where do we put the initializations so it doesn't run them on a reload (u cant use an IF statement in
public class lort : System.Web.UI.WebControls.WebParts.WebPart
it has to be in a function...) that' s why we tried using stateview...
mads
General Fault
The ASP.NET (and therefore SharePoint) life cycle is interesting, isn't it But it is important to understand in order to get things to work.
I am working from memory here, but IIRC the basic life cycle is as follows:
Initialize (page first, then controls, including CreateChildControls)
ViewState is recalled
Load
Page/Control Events are handled (like Click, OnChange, etc)
PreRender
Render
Unload
The important thing to remember is that for ViewState and Control Events to work properly, the control must be created/initialized before ViewState is loaded. This is the primary purpose of the CreateChildContols method. To create/initialize the controls that are to recieve the ViewState. Remember that the entire object graph of a page is recreated on each page load (i.e. button click) so for WebPart and custom control, they have to create/initialize their own controls. If this is done properly in the CreateChildControls, ASP.NET can hook them up to the ViewState and ControlEvents properly. So far all of this is needed to begin processing the logic in the control.
As a result of the events that occur in the control, the state of the control can change. This can be handled in the control events, but many time I find it more useful to make use of the PreRender to set the new state for the control (set TextBoxes, GridViews, etc.).
Then the <HTML> for the control is created in the Render method. It is best practice to not change the state of the child controls in this method, but to use the Render method to output the <HTML> for the child controls that have been previously modified.
I hope that this explanation sheds some light and does not confuse.
jkita
Ultimate
Some points to note:
Dont call EnsureChildControls() in Load event. Call it from RenderContent() or Render().
Also there is no need to call Load if page is postback.
Instantiating controls and adding items to controls should be done in CreateChildControls not in class or Load event.
hth
AndersR
ps. specielt navn til en klasse :p
Oskar2
here's some code...
public class lort : System.Web.UI.WebControls.WebParts.WebPart
{
System.Web.UI.WebControls.TextBox Titel = new TextBox();
System.Web.UI.WebControls.TextBox Note = new TextBox();
System.Web.UI.WebControls.DropDownList Status = new DropDownList();
System.Web.UI.WebControls.DropDownList Kategori = new DropDownList();
System.Web.UI.WebControls.Calendar Dato = new Calendar();
System.Web.UI.WebControls.ListBox Kontakt = new ListBox();
System.Web.UI.WebControls.ListBox Projekt = new ListBox();
System.Web.UI.WebControls.ListBox Referencer = new ListBox();
System.Web.UI.WebControls.Button Forrige = new Button();
System.Web.UI.WebControls.Button Nste = new Button();
System.Web.UI.WebControls.Button Udfr = new Button();
System.Web.UI.WebControls.Button Afbryd = new Button();
System.Web.UI.WebControls.Label TitelLb = new Label();
System.Web.UI.WebControls.Label NoteLb = new Label();
System.Web.UI.WebControls.Label StatusLb = new Label();
System.Web.UI.WebControls.Label KategoriLb = new Label();
System.Web.UI.WebControls.Label DatoLb = new Label();
System.Web.UI.WebControls.Label KontaktLb = new Label();
System.Web.UI.WebControls.Label ProjektLb = new Label();
System.Web.UI.WebControls.Label ReferencerLb = new Label();
protected override void Load(EventArgs e)
{
EnsureChildControls();
Dato.SelectedDate = DateTime.Today;
TitelLb.Text = "titel:";
Titel.Width = 400;
Titel.Wrap = true;
Titel.Height = 40;
Titel.TextMode = TextBoxMode.MultiLine;
DatoLb.Text = "Dato:";
Dato.SelectionMode = CalendarSelectionMode.Day;
Dato.ShowNextPrevMonth = true;
Dato.Enabled = true;
StatusLb.Text = "Status:";
Status.Width = 400;
Status.Items.Add("");
Status.Items.Add("Under behandling");
Status.Items.Add("Sagen er afsluttet");
KategoriLb.Text = "Kategori:";
Kategori.Width = 400;
ReferencerLb.Text = "Reference:";
Referencer.Items.Add("Growbusiness Administrator");
Referencer.Width = 400;
Referencer.Height = 20;
ProjektLb.Text = "Projekt:";
Projekt.Width = 400;
Projekt.Height = 20;
KontaktLb.Text = "Kontakt:";
Kontakt.Width = 400;
Kontakt.Height = 20;
NoteLb.Text = "Note:";
Note.Width = 400;
Note.Height = 100;
Note.TextMode = TextBoxMode.MultiLine;
Forrige.Text = "Forrige";
Nste.Text = "Nste";
Udfr.Text = "Udfr";
Afbryd.Text = "Afbryd";
}
protected override void CreateChildControls()
{
base.CreateChildControls();
Controls.Add(Dato);
Controls.Add(Nste);
Controls.Add(Forrige);
Controls.Add(Udfr);
Controls.Add(Afbryd);
Dato.SelectionChanged += new EventHandler(Selection_Changed);
Nste.Click += new EventHandler(Nste_Click);
Forrige.Click += new EventHandler(Forrige_Click);
Udfr.Click += new EventHandler(Udfr_Click);
Afbryd.Click += new EventHandler(Afbryd_Click);
}
protected override void OnPreRender(EventArgs e)
{
if (Page.IsPostBack)
{
}
else
{
Forrige.Enabled = false;
}
}
protected override void Render(HtmlTextWriter output)
{
output.Write("<table><tr><td valign=top align=right width=300>");
TitelLb.RenderControl(output);
output.Write("</td><td align=left>");
Titel.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
DatoLb.RenderControl(output);
output.Write("</td><td align=left>");
Dato.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
StatusLb.RenderControl(output);
output.Write("</td><td align=left>");
Status.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
KategoriLb.RenderControl(output);
output.Write("</td><td align=left>");
Kategori.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
ReferencerLb.RenderControl(output);
output.Write("</td><td align=left>");
Referencer.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
ProjektLb.RenderControl(output);
output.Write("</td><td align=left>");
Projekt.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
KontaktLb.RenderControl(output);
output.Write("</td><td align=left>");
Kontakt.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td valign=top align=right>");
NoteLb.RenderControl(output);
output.Write("</td><td align=left>");
Note.RenderControl(output);
output.Write("</td></tr>");
output.Write("<tr><td colspan=2 align=right>");
Forrige.RenderControl(output);
Nste.RenderControl(output);
Udfr.RenderControl(output);
Afbryd.RenderControl(output);
output.Write("</td></tr></table>");
}
private void Selection_Changed(Object sender, EventArgs e)
{
Dato.SelectedDate = Dato.SelectedDate;
}
private void Nste_Click(object sender, EventArgs e)
{
Nste.Enabled = false;
Forrige.Enabled = true;
Note.Text = Titel.Text;
}
private void Forrige_Click(object sender, EventArgs e)
{
Nste.Enabled = true;
Forrige.Enabled = false;
}
private void Udfr_Click(object sender, EventArgs e)
{
}
private void Afbryd_Click(object sender, EventArgs e)
{
}
}
Hope this gives you an idea of what we are doing wrong, hope you can give us a push in the right direction
Thiru_
Are the controls going back to their default values If so try the below...
try:
protected override void Load(EventArgs e)
{
if(!Page.IsPostBack)
{
// set control values in here...
}
}
Maestro
are you adding the controls to the webparts controls collection
If there's not too much code, paste it here for us to see
Nick
Cyril839
I always use Init, Pre-Render and then Render to ensure I can seperate the parts I need to :-)
protected override void OnInit(EventArgs e){
// Check for Page Edit Mode in SharePoint if(HttpContext.Current.Request.QueryString["Mode"] == "Edit")pageeditmode =
true; try{
string strzoom = this.Context.Request.Cookies[ "map_CurrentZoom" ].Value;currentZoom = Decimal.Parse(strzoom);
}
catch{currentZoom=MapOffset;}
if(pageeditmode==false)
{
try{
outZoom = currentZoom * MapZoomFactor;
}
catch{
// divide by zeroMapZoomInButton.AnchorUrl =
MapZoom('" + inZoom.ToString() +"')";MapZoomInButton.IconUrl =
base.ResourcePath + "/zoomin.gif";MapZoomOutButton.AnchorUrl =
MapZoom('" + outZoom.ToString() +"')";MapZoomOutButton.IconUrl =
base.ResourcePath + "/zoomout.gif";MapResetButton.AnchorUrl =
MapReset( )";MapResetButton.IconUrl =
base.ResourcePath + "/reset.gif";BuildToolbar(MapZoomInButton, MapZoomOutButton, MapResetButton);
}
base.OnInit (e);
}
protected override void CreateChildControls()
{
base.CreateChildControls ();
this.Controls.Add( MenuDiv );
//MainView
Table MainTable = new Table();MainTable.Width =
Unit.Parse( "100%" );MainTable.CellPadding = 2;
MainTable.Attributes.Add(
"align","center"); TableRow MainTableRow = new TableRow(); TableCell MainTableCell = new TableCell();MainTableCell.HorizontalAlign =
HorizontalAlign.Center;LinkTableRow.Cells.Add(LinkTableCell);
MainTableRow.Cells.Add( MainTableCell );
MainTable.Rows.Add( MainTableRow );
MainTable.Rows.Add( LinkTableRow );
MainViewDiv.Controls.Add(MainImageView);
MainTableCell.Controls.Add( MainViewDiv );
this.Controls.Add( MainTable );}
protected override void OnPreRender(EventArgs e){
base.OnPreRender (e); if ( !Page.IsClientScriptBlockRegistered( "environmental" ) ){
this.Page.RegisterClientScriptBlock( "environmental", string.Format( "<script language='javascript' src='{0}/environmental.js'></script>", base.ResourcePath ) );}
}
protected override void RenderWebPart(HtmlTextWriter output){
EnsureChildControls( );
try{
if(pageeditmode==false){
if( fullFacility != null ){
try{
// get the Current Zoom Level from the cookie if it is set decimal facilityLatitude = decimal.Parse(fullFacility.Latitude); decimal facilityLongitude = decimal.Parse(fullFacility.Longitude); string facilityName = fullFacility.Name; // Call the Web Service to get the Image Map // TODO: Add Web part Cache to retrieve the image URL from Cache for 4 minutes // since that is the length of time that the Mapping Service retains the images for. string imageURL = GetMapURL(fullFacility.Id,facilityLatitude, facilityLongitude, facilityName, _mapWidth, _mapHeight, currentZoom);MainImageView.Height = _mapHeight;
MainImageView.Width = _mapWidth;
MainImageView.ImageUrl = imageURL;
MainImageView.AlternateText = facilityName +
"- Lat: " + fullFacility.Latitude + " Long: " + fullFacility.Longitude;MainImageView.Attributes.Add(
"onclick","MapZoomImage('" + MainViewDiv.ClientID + "','" + inZoom.ToString() + "')"); if(showMapDetails==true){
// Set up a table for the various items to display below the map Table MapDetailTable = new Table();MapDetailTable.Width =
Unit.Parse( "100%" );MapDetailTable.CellPadding = 2;
MapDetailTable.Attributes.Add(
"align","center");MapDetailTable.Attributes.Add(
"border-color","#CCCCCC");MapDetailTable.Attributes.Add(
"border-width","1px");MapDetailTable.Attributes.Add(
"border-style","solid");MapDetailTable.Attributes.Add(
"PADDING","2px"); TableRow MapDetailRow = new TableRow(); TableCell MapDetailCell = new TableCell();MapDetailCell.HorizontalAlign =
HorizontalAlign.Center;MapDetailCell.Controls.Add(
new LiteralControl ("<BR>Latitude: " + fullFacility.Latitude.ToString()));MapDetailCell.Controls.Add(
new LiteralControl ("<BR>Longitude: " + fullFacility.Longitude.ToString()));MapDetailCell.Controls.Add(
new LiteralControl ("<BR>Current Map Layer: " + CurrentMapLayer.ToString()));MapDetailRow.Controls.Add(MapDetailCell);
MapDetailTable.Rows.Add( MapDetailRow );
LinkTableCell.Controls.Add( MapDetailTable );
}
if(showLiveLink==true){
// Set up a table for the various items to display below the map Table LiveDetailTable = new Table();LiveDetailTable.Width =
Unit.Parse( "100%" );LiveDetailTable.CellPadding = 2;
LiveDetailTable.Attributes.Add(
"align","center"); TableRow LiveRow = new TableRow(); TableCell LiveCell = new TableCell();LiveCell.HorizontalAlign =
HorizontalAlign.Center; // Set the "View On Map" Link for Windows Live string _liveMapLink = string.Format(_liveMapURL, fullFacility.Latitude, fullFacility.Longitude, fullFacility.Name, fullFacility.Name);LiveCell.Controls.Add(
new LiteralControl ("<a href='" + _liveMapLink + "' target='_new'><IMG src=\"" + base.ResourcePath + "/WindowsLive.jpg\" border=\"0\"</a>"));LiveRow.Cells.Add( LiveCell );
LiveDetailTable.Rows.Add( LiveRow );
LinkTableCell.Controls.Add( LiveDetailTable );
}
if(showGoogleLink==true){
Table GoogleDetailTable = new Table();GoogleDetailTable.Width =
Unit.Parse( "100%" );GoogleDetailTable.CellPadding = 2;
GoogleDetailTable.Attributes.Add(
"align","center"); TableRow GoogleRow = new TableRow(); TableCell GoogleCell = new TableCell();GoogleCell.HorizontalAlign =
HorizontalAlign.Center; // Set the "View On Map" Link for Google Maps string _googleMapLink = string.Format(_googleMapURL, fullFacility.Latitude, fullFacility.Longitude, fullFacility.Name, fullFacility.Name);GoogleCell.Controls.Add(
new LiteralControl ("<a href='" + _googleMapLink + "' target='_new'><IMG src=\"" + base.ResourcePath + "/GoogleMaps.jpg\" border=\"0\"</a>"));GoogleRow.Cells.Add( GoogleCell );
GoogleDetailTable.Rows.Add( GoogleRow );
LinkTableCell.Controls.Add( GoogleDetailTable );
}
}
catch(Exception ex){
// Unable to retrieve Image for Selected FacilityMenuDiv.Visible =
false; //MainImageView.Visible = false;MainImageView.Height = _mapHeight/2;
MainImageView.Width = _mapWidth/2;
MainImageView.ImageUrl =
base.ResourcePath + "/Image_Unavailable.jpg";MainImageView.AlternateText =
"Unable to Retrieve Facility Map";MainViewDiv.Controls.Add(
new LiteralControl ( "<table width=\"100%\" cellpadding=\"2\" class=\"ms-stylebox\" >" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "<td>Unable to Retrieve Image for Selected Facility</td>" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "</table>" ) );logger.Error(
"Unable to Set Facility Map: " + ex.Message);}
}
else{
MenuDiv.Visible =
false;MainImageView.Visible =
false;MainViewDiv.Controls.Add(
new LiteralControl ( "<table width=\"100%\" cellpadding=\"2\" class=\"ms-stylebox\" >" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "<td>No facility currently selected</td>" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "</table>" ) );}
}
else{
// We are in SharePoint Edit ModeMainImageView.Visible =
false;MainViewDiv.Controls.Add(
new LiteralControl ( "<table width=\"100%\" cellpadding=\"2\" class=\"ms-stylebox\" >" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "<td>Edit Mode: Web parts do not render in Page Edit Mode</td>" ) );MainViewDiv.Controls.Add(
new LiteralControl ( "</table>" ) );}
}
catch( Exception ex ){
output.Write( ex.ToString( ) );
}
base.RenderWebPart( output );}
windypoint
Hello,
I am exactly at the same point and I found out this here:
the called RenderControl() methods of the objects create simple HTML , without the needed HTML attributes for the ASP.NET code-behind functionality. So your code always creates fresh new HTML controls, every time. Your event handler methods will also never be called. Your TextBoxes are always empty, and so on.
My very first try of using ASP.NET server controls was to use CreateChildControls() and add there *all* controls to the ControlCollection. I never touched a rendering method like Render() or RenderContents(). And it worked!
But ..... :-((
When I added a Button to the ControlCollection and the Button had an click-EventHandler, then I found out that the code of the EventHandler method is called *AFTER* the call of the CreateChildControl() method :-((
It means that the complete content is finished through CreateChildControls(), and then the click-EventHandler will be called. How smart is this Too late ....because the code of the EventHandler now cannot change the content because it is already created through CreateChildConttols().
When I created my controls in the way like you did, with RenderControls() inside the overridden Render() method, then I get simple HTML.
Third try:
I put *all* control creation from CreateChildControls() into RenderControls() method, there I fill the ControlContainer and then finally call "base.RenderContents();". It worked, but..... :-((( ......no EventHandler is working! I do have the same effect of a not working page-reload! The whole ASP.NET functionality is not working.
Regards,
PinkyLover
Dave Waterworth
Hi everyone!
I'm having a similar problem, so I was wondering if anyone could point me out a solution...
Here's my code:
protected override void CreateChildControls(){
m_txtCreationDate = new TextBox();m_txtCreationDate.Text =
""; Controls.Add(m_txtCreationDate);}
protected
override void LoadViewState(object savedState){
EnsureChildControls();
object[] state = null; if (savedState != null){
state = (
object[])savedState; base.LoadViewState(state[0]);m_txtCreationDate.Text = state[1].ToString();
}
}protected override object SaveViewState()
{
EnsureChildControls();
object[] state = new object[4];
state[0] = base.SaveViewState();
state[1] = m_txtCreationDate.Text;
return state;
}
protected
override void RenderWebPart(HtmlTextWriter writer){
writer.Write("ViewState value: "+ m_txtCreationDate.Text + "<br/>");
CreationDate = "02/10/2007";
m_txtCreationDate.Text = CreationDate;
}
Everytime I refresh, the output I get is "ViewState value: "
I'm clearly missing something, can anyone help me