Hi,
I created a working function wich i want to convert to a class. After some adjustments things work fine, except for two: ViewState and FindControl. The class needs to save a string to ViewState and retrieve it again when a button is clicked. FindControl is used in the class to retrieve a control from a Form (by its ID: the string from ViewState)in which the class is initiated. Here is my class so far:
Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Navigatie
{
public class BtnImageChange : ImageButton
{
public string strPreviousBtn = " ";
private const string ACTIVE_IMG_SUPL = "_a";
ImageButton btnPreviousButton = new ImageButton();
public BtnImageChange()
{
System.Diagnostics.Trace.WriteLine(" ");
System.Diagnostics.Trace.WriteLine("----------- BtnImageChange Opnieuw Geinitieerd -----------");
//this.EnableViewState = true;
if (this.EnableViewState)
{
System.Diagnostics.Trace.WriteLine("ViewState on startup contains: " + (string)ViewState["strActiveBtnID"]);
}
this.EnableViewState = true;
}
public void ChangeImage(object sender, ImageClickEventArgs e)
{
//set image of current active button to active
ImageButton btnToActive = (ImageButton)sender;
string strInActiveUrl = btnToActive.ImageUrl;
string [] arrSplitInActiveString = strInActiveUrl.Split(new Char [] {'.'});
strInActiveUrl = arrSplitInActiveString[0] + ACTIVE_IMG_SUPL + "." + arrSplitInActiveString[1];
btnToActive.ImageUrl = strInActiveUrl;
strPreviousBtn = (string)this.ViewState["strActiveBtnID"];
System.Diagnostics.Trace.WriteLine("viewstate after postback : " + strPreviousBtn + " button ID = " + btnToActive.ID);
if(strPreviousBtn != null)
//Change image of previous button to inactive
{
System.Diagnostics.Trace.WriteLine("viewstate after postback and inside if : " + strPreviousBtn);
btnPreviousButton = FindControl(strPreviousBtn) as ImageButton;
System.Diagnostics.Trace.WriteLine(btnPreviousButton.ImageUrl);
string strActiveUrl = btnPreviousButton.ImageUrl;
System.Diagnostics.Trace.WriteLine(btnPreviousButton.ImageUrl);
string strNewInActiveUrl = strActiveUrl.Remove((strActiveUrl.Length-6),ACTIVE_IMG_SUPL.Length);
btnPreviousButton.ImageUrl = strNewInActiveUrl;
}
this.ViewState["strActiveBtnID"] = btnToActive.ID;
strPreviousBtn = (string)ViewState["strActiveBtnID"];
System.Diagnostics.Trace.WriteLine("viewstate after setting : " + strPreviousBtn);
}
}
}
Now the viewstate saves fine, but is gone after the postback and the findcontrol returns null. My guess is that I should be pointing to the ViewState and the buttons in the form. If so, how do I do that and if not does anyone have another idea?