• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1417
  • Last Modified:

Event Handling issue in Code behind c# asp.net

Does anyone know who to overcome the persistent event_handling dynamic control problem in asp.net/C#.

I assign an event handler to controls. They only fire once then the new controls created do not fire. The event handler is lost. I know there is a way to preserve this creating a session variable. I just cannot see to work it from there.

In the below example the Linq -> XML is fine. This has nothing to do with AJAX.

I am preserving the linkButtons in the following Generic List:

 List<LinkButton> persistControls = new List<LinkButton>();

I just don't know how to fire the event_handler based on persistControls content with regards to what was selected on the front end ...

string ctrlname = Page.Request.Params["__EVENTTARGET"];

Any help or direction would be greatly appreciated. I know I am close just lacking in the final piece of knowledge. Thank you.
Here is the XML:
 
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<sites>
  <siteName>Manchester</siteName>
  <siteName>London<siteName>Greenwich<siteName>Charlton</siteName></siteName></siteName>
</sites>
 
Here is the front end:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link href="DirectoryTesterStyles.css" rel="stylesheet" type="text/css" />
    <title>Persistent State Event Handling Issue</title>
</head>
<body>
    <form id="form1" runat="server">
        <ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server" />
        <div> 
                                <asp:Panel ID="myContentPanel"  CssClass ="contentDisplay" runat="server" >
                                </asp:Panel> 
        </div>
    </form>
</body>
</html>
 
Here is the code behind:
 
public partial class _Default : System.Web.UI.Page 
{
    List<LinkButton> persistControls = new List<LinkButton>();
 
    protected void Page_Load(object sender, EventArgs e)
    {
            
            string ctrlname = Page.Request.Params["__EVENTTARGET"];
            if (Session["persistControls"] != null)
            {
                persistControls = (List<LinkButton>)Session["persistControls"]; // pull them out of the session
                int count = 0;
                foreach (LinkButton lc in persistControls)
                {
                    myContentPanel.Controls.Add(lc); // and push them back into the page
                    myContentPanel.Controls.Add(new LiteralControl("<br /><br />")); // for formatting
                    count++;
                }
            }
 
        
            DirectoryConstructor();
 
    }
 
    private void DirectoryConstructor()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("C:/DitectoryTester/App_Data/structure.xml");
 
        foreach (XmlNode node in xmlDoc.SelectNodes("/sites/siteName"))
        {
            Label myLabel = new Label();
            myLabel.CssClass = "nameOutput";
            myLabel.Text = node.ChildNodes[0].Value;
 
 
            LinkButton myLink = new LinkButton();
            string myString = Convert.ToString(node.ChildNodes[0].Value);
            myLink.ID = " " + myString;
            myLink.Text = myString;
            myLink.CssClass = "displayImage";
            myLink.Controls.Add(myLabel);
            myLink.Controls.Add(new LiteralControl("<br />"));
 
            myLink.Click += new EventHandler(myLink_Click);
 
            myContentPanel.Controls.Add(myLink);
 
            persistControls.Add(myLink);// add it to the list
            Session["persistControls"] = persistControls;
        }
    }
 
 
 
    protected void myLink_Click(object sender, EventArgs e)
    {
        myContentPanel.Controls.Clear();
        XDocument x = XDocument.Load(Server.MapPath("~") + "/App_Data/structure.xml");
        IEnumerable<XElement> city = from p in x.Descendants() where p.Value.Trim().StartsWith(((LinkButton)sender).Text) select p;
 
        IEnumerable<XElement> sub_cities = from p in city.Elements("siteName") select p;
 
        persistControls.Clear();
        foreach (XElement xe in sub_cities)
        {
            xe.Descendants().Remove();
 
            Label myLabel = new Label();
            myLabel.CssClass = "nameOutput";
            myLabel.Text = xe.Value;
 
            LinkButton myLink = new LinkButton();
            string myString = Convert.ToString(xe.Value);
            myLink.ID = " " + myString;
            myLink.Text = myString;
            myLink.CssClass = "displayImage";
            myLink.Controls.Add(myLabel);
            myLink.Controls.Add(new LiteralControl("<br />"));
            myLink.CommandArgument = persistControls.Count.ToString();
            myLink.Click += new EventHandler(myLink_Click);
            
 
            myContentPanel.Controls.Add(myLink);
 
 
            persistControls.Add(myLink);// add it to the list
            Session["persistControls"] = persistControls;
        }
    }

Open in new window

0
metta0_3
Asked:
metta0_3
  • 2
1 Solution
 
OBonioCommented:
I think you may need to recreate the controls before the Page_Load event.  Try putting it in the LoadViewState event.



    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        // Recreate dynamic controls here.
    }

Open in new window

0
 
metta0_3Author Commented:
I think you may be on to something here. I cant seem to break LoadViewState at the moment. Have you come across this scenario before?? Thanks for info.
0
 
metta0_3Author Commented:
This was very useful and was exactly what I was looking for. Thank you.
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now