Question

I'm using ASP.NET TreeView Control in my page. I build the tree, by using the CreateChildControls() (override).

protected override void CreateChildControls()
    {
        base.CreateChildControls();
        TVOrg = this.FindControl<TreeView>("TVOrg");


        try
        {
            DataTable itemsTable = CreateTable();
            if (itemsTable != null)
            {
                XmlDocument xmlDoc = CreateXML(CreateDataRow(itemsTable));
                if (xmlDoc != null)
                    FillTreeViewFromXML(xmlDoc);
            }
        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    OnPreRender(), {0}", ex.Message));
        }
    }

Inside this method, I'm getting the hierarchy for the tree from an sql view.

    public DataTable CreateTable()
    {
        DataTable dataTable = new DataTable();
        try
        {
            // base.DbConnection.Open();
            dataTable.Columns.Add(idColumnName);
            dataTable.Columns.Add(ParentColumnName);
            dataTable.Columns.Add(valueColumnName);
            List<DBParameter> prms = new List<DBParameter>();
            dataTable = DBUtil.ExecuteReader("sp_GetTreeViewHierarchy", prms.ToArray(), System.Data.CommandType.StoredProcedure);


        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    CreateTable(), {0}", ex.Message));
        }
        return dataTable;
    }

after that I'm creating an XML file (in memory) and using the XmlDataSource to bind the data.

public DataRow[] CreateDataRow(DataTable table)
    {
        // Use the Select method to sort the rows by ParentID
        DataRow[] SortedRows = null;
        try
        {
            SortedRows = table.Select("", levelColumnName + "," + valueColumnName + "," + ParentColumnName);
        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    CreateDataRow(), {0}", ex.Message));
        }


        return SortedRows;
    }


    public XmlDocument CreateXML(DataRow[] SortedRows)
    {
        // create an XmlDocument (with an XML declaration)
        XmlDocument XDoc = new XmlDocument();
        try
        {
            XmlDeclaration XDec = XDoc.CreateXmlDeclaration("1.0", null, null);
            XDoc.AppendChild(XDec);


            // iterate through the sorted data
            // and build the XML document
            foreach (DataRow Row in SortedRows)
            {
                XmlElement NewNode = XDoc.CreateElement("_" + Row[idColumnName].ToString());
                NewNode.SetAttribute(idColumnName, Row[idColumnName].ToString());
                NewNode.SetAttribute(ParentColumnName, Row[ParentColumnName].ToString());
                NewNode.SetAttribute(valueColumnName, Row[valueColumnName].ToString());


                // special case for top level node
                if (int.Parse(Row[ParentColumnName].ToString()) == 0)
                    XDoc.AppendChild(NewNode);  // root node
                else
                {
                    // use XPath to find the parent node in the tree
                    String SearchString;
                    SearchString = String.Format("//*[@" + idColumnName + "=\"{0}\"] ", Row[ParentColumnName].ToString());
                    XmlNode Parent = XDoc.SelectSingleNode(SearchString);


                    if (Parent != null)
                        Parent.AppendChild(NewNode);
                }
            }
        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    CreateXML(), {0}", ex.Message));
        }
        return XDoc;
    }


    public void FillTreeViewFromXML(XmlDocument XDoc)
    {
        try
        {
            // we cannot bind the TreeView directly to an XmlDocument
            // so we must create an XmlDataSource and assign the XML text
            XmlDataSource XDdataSource = new XmlDataSource();
            XDdataSource.ID = DateTime.Now.Ticks.ToString();  // unique ID is required
            XDdataSource.Data = XDoc.OuterXml;


            // we want the full name displayed in the tree so 
            // do custom databindings
            TreeNodeBinding Binding = new TreeNodeBinding();
            Binding.TextField = valueColumnName;
            Binding.ValueField = idColumnName;
            Binding.Target = "#";
            TVOrg.DataBindings.Add(Binding);


            // Finally! Hook that bad boy up!       
            TVOrg.DataSource = XDdataSource;
            TVOrg.DataBind();
        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    FillTreeViewFromXML(), {0}", ex.Message));
        }
    }

I create a new node by filling a form, and than i call this method.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            var entityIdHidden = this.FindControl<HiddenField>("SelectedNodeId");


            if (entityIdHidden != null)
                if (entityIdHidden.Value == "")
                    if (!CheckifSiteAlreadyExists())
                        return;


            if (!CheckIfEntityHasParent())
                return;


            var user = AuthenticationManager.LoggedInUser;
            WorkflowAPI api = new WorkflowAPI();


            Dictionary<string, object> entityFields = GetEntityControls();
            AttachmentEntity image = AttchmentItem("AsyncFileUpload2");


            if (image != null)
                entityFields.Add("fldImage", image);


            int entityId = 0;
            bool isSite = CheckIfEntityIsSite();
            if ((entityIdHidden != null) && (!string.IsNullOrEmpty(entityIdHidden.Value)))
            {
                int.TryParse(entityIdHidden.Value, out entityId);
            }
            api.UpdateACtivityFields(WorkflowInstanceId, user, this.GetFormUIViewModel().ActivityInstance, entityFields, entityId, "EntityType");


            List<DBParameter> prms = new List<DBParameter>();
            prms.Add(new DBParameter(System.Data.DbType.Int32, WorkflowInstanceId, "iwf"));
            prms.Add(new DBParameter(System.Data.DbType.Int32, entityId, "entityId"));
            int.TryParse(DBUtil.ExecuteScalar("USP_TEN_Entities_UpdateDynamicsValues", prms.ToArray(),
                CommandType.StoredProcedure).ToString(), out entityId);


            Dictionary<string, object> siteFields;
            if (isSite)
            {
                siteFields = GetSiteControls();
                siteFields.Add("fldParentid", entityId);
                api.UpdateACtivityFields(WorkflowInstanceId, user, this.GetFormUIViewModel().ActivityInstance, siteFields, entityId, "SiteDetails");
            }


            entityIdHidden.Value = entityId.ToString();
            this.CreateChildControls();


            //Response.Redirect(Request.RawUrl);
        }
        catch (Exception ex)
        {
            PNMsoft.Sequence.Diagnostics.DiagnosticUtility.EventLog.LogError(String.Format("TreeViewOrg.aspx:    btnSave_Click(), {0}", ex.Message));
        }
    }

This method update the database with the details I've entered.

As you can see in the btnSubmit method at the end, i call the CreateChildControls() method because i need to update the tree with the latest data. The problem is that i'm losing the focus and SelectedNode.

How can i return to the last Selected Node.

Était-ce utile?

La solution

First of all please check that your CreateChildControls() function is within IsPostBack() condition or not. If yes then go through this link - Set Node in Treeview - Which will guide you how to do that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top