2

I use RadTreeView in my master page :

but i face the following problem :

I lose my selections when i click on the nodes of the tree view .and every time i click on the node it makes (Response.Redirect("...")) which make the master entering the (!Page.IsPostback) every time and bind the tree view again so i lose my selections .

How to fix this problem .

My .aspx :

 <telerik:RadTreeView ID="rtv_cm" runat="server" OnNodeExpand="rtv_cm_NodeExpand"
                OnNodeClick="rtv_cm_NodeClick" Skin="WebBlue">
 </telerik:RadTreeView>

My .cs :

 protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["emp_num"] != null && !string.IsNullOrEmpty(Session["emp_num"].ToString()))
            {

                if (!Page.IsPostBack)
                {

                    LoadRootNodes(rtv_cm, TreeNodeExpandMode.ServerSide);
                }
            }
            else
            {
                Response.Redirect("Frm_login.aspx");
            }
        }

protected void rtv_cm_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            dt_childs = (DataTable)Session["dt_childs"];
            IEnumerable<DataRow> result = from myRow in dt_childs.AsEnumerable()
                                          where myRow.Field<string>("task_id").TrimEnd() == e.Node.Value.TrimEnd()
                                          select myRow;
            if (result != null)
            {
                if (!string.IsNullOrEmpty(result.ElementAtOrDefault(0).Field<string>("page_name")))
                {
                    Response.Redirect(result.ElementAtOrDefault(0).Field<string>("page_name").TrimEnd(), false);
                }
            }
        }

How I get The menu :

  private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            dt = Menu_db.GetMenu(Session["emp_num"].ToString(), CMSession.Current.db_code);
            IEnumerable<DataRow> result = from myRow in dt.AsEnumerable()
                                          where myRow.Field<string>("task_id").TrimEnd() == "0"
                                          select myRow;
            if (result != null && result.Count()>0)
            {
                DataTable dt_roots = result.CopyToDataTable<DataRow>();
                Session["dt"] = dt;
                Session["dt_roots"] = dt_roots;

                foreach (DataRow row in dt_roots.Rows)
                {
                    RadTreeNode node = new RadTreeNode();

                    node.Text = row["task_name"].ToString().TrimEnd();
                    node.Value = row["task_id"].ToString().TrimEnd();
                    if (Convert.ToInt32(row["count"]) > 0)
                    {
                        node.ExpandMode = expandMode;
                    }
                    treeView.Nodes.Add(node);
                }
            }
        }
Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392

4 Answers4

3

HTTP is what's known as a "stateless protocol". Basically, it's as if the server has a severe case of Alzheimer's disease (no disrespect intended). The server answers your query, but then forgets you were ever there.

When HTTP was used primarily for fetching static documents, this posed no problem, but web applications require some kind of state. There are many ways this is accomplished, but ASP.NET typically makes heavy use of the "ViewState". The view state is simply an <input type="hidden"> tag which contains base-64 formatted byte code. (If you view the source of your rendered HTML page in the browser, you see it - named "__VIEWSTATE"). When the user resubmits the form (by clicking a button, etc), the viewstate data is sent back to server. Basically, it's like reminding the server about what it told you last time. This is how TextBoxes and GridViews are able to seemingly maintain their state between postbacks - they store their state in the "viewstate".

The problem with the viewstate, though, is that it can be easily lost. You must submit the form or the viewstate will not be persisted. If you use an anchor tag or Request.Redirect, you are side-stepping the form and hitting a web page all on your own and, in the process, you are not passing any of the viewstate along.

There is often no way to avoid this, so there are other ways to store your application's state. But, unlike the viewstate, this is something you must do manually for each and every value that you want to persist. You can store the data in a cookie, you can store the data on the server (using Server["key"] or Session["key"]) or you can persist the data in something more concrete, like a database or a text file. All of this must be done manually, however, and then you must reload the data when you reload the page.

In your case, you may want to guess which item was selected based on the current page (since the treeview items and pages seem to be linked) and set the selected item explicitly. If that's not feasible, you could try storing the selected item in the Session, using something like Session["Master_SelectedTreeViewItem"] = treeViewItem.Id;. Then, in Page_Load, get this value (careful, it may be null) and then set the corresponding treeview item as selected.

I would post more code examples, but you haven't provided the code where you are loading the treeview, etc, so it would be difficult to do.

Further Info

ASP.NET State Management Overview (MSDN)

JDB
  • 25,172
  • 5
  • 72
  • 123
  • Thanks a lot .I edit my question and write more code .Could u clarify more by code how to do this? and please look to this link . it uses the `RadTreeView`.And after clicking on the node , it makes postback however it maintains the state. http://demos.telerik.com/aspnet-ajax/treeview/examples/programming/serversideapi/defaultcs.aspx – Anyname Donotcare Oct 07 '12 at 08:28
  • 1
    Yes, it will maintain state on a postback, but it will not maintain state when you switch to different page, or use another mechanism (such as Response.Redirect) to "postback" to the same page. Please read the article I linked to for more information. – JDB Oct 07 '12 at 21:17
  • I try to access my treeview in every page which use the master page in which the `treeview` exist.storing the selection in the session in my master page as u suggested. But i get `object null reference exception` When i try to `FindByValue(Session["Master_SelectedTreeViewItem"].ToString()).Selected = true;` I try to find which object is null then when i call the method `GetAllNodes()`,I found the `count = 0` No nodes !! – Anyname Donotcare Oct 09 '12 at 03:00
  • As I said, you must be careful because Session["key"] may be null. You are attempting to call the `ToString()` function on a null value which will throw a NullReferenceException. Try `(Session["Master_SelectedTreeViewItem"] ?? "").ToString()` – JDB Oct 09 '12 at 03:10
  • no `Session["Master_SelectedTreeViewItem"] ` is n't null just the treeview has no nodes at all to set the selection ! – Anyname Donotcare Oct 09 '12 at 03:15
  • You may want to read up on the [ASP.NET Page Life Cycle](http://msdn.microsoft.com/en-us/library/ms178472.aspx) – JDB Oct 09 '12 at 03:19
  • Could U check how i load my treeview in my masterpage please ? I don't know why the count is 0 in my pages . I access my tree view in a correct way but the nodes count =0 – Anyname Donotcare Oct 09 '12 at 03:25
  • 1
    This is getting beyond a technical question and into debugging your code. You may need to spend some time reviewing it (and the life cycle article I already linked to). I can't explain how to program in ASP.NET on a forum - especially in the comments section. – JDB Oct 09 '12 at 03:28
  • if you need to access your treeview from child pages, on the child page do this: MasterPage myMaster = this.Page.Master; RadTreeView treeview = (RadTreeView)myMaster.FindControl("rtv_cm"); – Ewerton Oct 11 '12 at 16:49
2

The only way i can think of is storing the selection in session and on (!Page.IsPostBack), look for that Session key and update your selection after the binding.

The problem you face is because essentially, trough your Redirect, you go to a different html page, so ViewState is out the window, nevermind that it is the same address.

Ioana O
  • 197
  • 1
  • 10
2

If you are binding the tree with urls that link to other page, append the selection using query string, then load the tree selection from the query string from the other page.

If you think that the second page you are redirecting to has same UI as the first, dont redirect instead load it on the same page with the new content for the selection, this will allow you to maintain the state in asp.net if the control supports view state.

Soori
  • 61
  • 5
  • Hi, can you please accept an answer when you find one acceptable. Click the tick. Thanks –  Oct 06 '12 at 20:14
1

I already had this problem, exactly same problem, needs to redirect on TreeViewItemClick.

I solve it storing the last selected item is session, and selection it again on page load.

Somethink like this

protected void rtv_cm_NodeClick(object sender, RadTreeNodeEventArgs e)
{
    Session["LastClickedNode"] = e.Node.Value;
    ...
}

and in your Load method, verifi ir the node needs to be selected, like this.

 private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
 {
     //... your code
     if (Session["LastClickedNode"] !=null)
     {
          if (row["task_id"].ToString().TrimEnd() == Session["LastClickedNode"].ToString())
          {
               node.Selected = true;
          } 
     }
 }

i think this will solve your problem.

Ewerton
  • 4,046
  • 4
  • 30
  • 56
  • in the page_load of master page or in the page load of the pages which i redirect to ?? I try to access my treeview in every page which use the master page in which the treeview exist.storing the selection in the session in my master page as u suggested. But i get object null reference exception When i try to `FindByValue(Session["Master_SelectedTreeViewItem"].ToString()).Selected = true;` I try to find which object is null then when i call the method `GetAllNodes()`,I found the `count = 0` No nodes !! – Anyname Donotcare Oct 11 '12 at 13:37
  • if you have your Tree View in your MasterPage, so you need to handle the storing and retrieve the "LastSelectedItem" in your MasterPage. You realy need to access the TreeView from child pages? – Ewerton Oct 11 '12 at 16:44
  • if you need to access your treeview from child pages, on the child page do this: MasterPage myMaster = this.Page.Master; RadTreeView treeview = (RadTreeView)myMaster.FindControl("rtv_cm"); – Ewerton Oct 11 '12 at 16:48
  • hmmm, I have already done all what u say but i get `No nodes` in the tree to set one of them with the session variable .Could u read the load part again and tell me how u load your tree view ?? like me or u bind on some data source ? more code please to clarify how u bind this ? – Anyname Donotcare Oct 11 '12 at 18:32
  • I see that you load the nodes from a linq expression, try to comment the where clause, even add a watch to "dt" variable e try to see if she was rows. if your "result" variable have "no rows" so the problem is in your DataSource. – Ewerton Oct 11 '12 at 20:37
  • no there are rows and the treeview has items but the problem is through postbacks i lose the user interactions – Anyname Donotcare Oct 23 '12 at 17:09