[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Help needed with treeview methode AfterSelect

Posted on 2011-03-13
14
Medium Priority
?
485 Views
Last Modified: 2013-12-17
Hi,

I have a treeview and a textbox on the form that is devided with a splitter.
The nodes in the treeview are loaded and saved to/from a database. Every
node is associated with a row of a database. I have add a new column called
Data. This is for the textbox. So when a user clicks on a node of a treeview
and put text in the textbox, the data in the textbox will be saved to the data-
base also. Who can help me with this? I know I have to use the treeview-event
AfterSelect. But I don't get further than this:

        private void tvNotes_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TextBox1.Text = ?????
        }

I have put all the code in the code-section, because I have no idea what is
relevant. I hope someone can help me?

Peter Kiers


private ContextMenu tvSampleMenu = new ContextMenu();
        private const string ImageIndexColumnName = "ImageIndex";
        private const string SelectedImageIndexColumnName = "SelectedImageIndex";
        private const string SortOrderColumnName = "SortOrder";
        private string DBName = "";
        private string DBConStr = "";

        public MainForm()
        {
            InitializeComponent();
        }
        //*----------------------------------------------------------*//
        private void MainForm_Load(object sender, EventArgs e)
	    {
         try
         {
        DBName = Application.StartupPath + @"\DBRoot.mdb";
        DBConStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";Data Source=" + DBName +";";
        tvSampleMenu.MenuItems.Add("Add Folder", new EventHandler(tvSampleRightClickInsFolder));
        tvSampleMenu.MenuItems.Add("Add Item", new EventHandler(tvSampleRightClickInsItem));
        tvSampleMenu.MenuItems.Add("Edit", new EventHandler(tvSampleRightClickEdit));
        tvSampleMenu.MenuItems.Add("Delete",new EventHandler(tvSampleRightClickDelete));
        LoadTree(tvNotes, GetHierarchy(DBConStr, 1));
           }
       catch (Exception err) 
         {  
           MessageBox.Show(err.Message);
         }
	    }
        //*----------------------------------------------------------*//
        private void LoadTree(TreeView tv, DataSet ds)
        {
            try
            {
                LoadFromDataSet(tv, ds, "Description");
                if (tv.Nodes.Count > 0)
                {
                    tv.Nodes[0].Expand();
                }
            }
            catch (Exception) 
            { 
                throw; 
            }
        }
        //*----------------------------------------------------------*//
        public static DataSet GetHierarchy(string connectionString, int modelID)
        {
            string sql = "";
            DataSet ds = null;
            try
            {
                sql = "select * from hierarchy ";
                sql += "  where modelid=" + modelID.ToString();
                sql += "  order by parentnodeid,sortorder asc";
                ds = GetDataSet(connectionString, sql);
                SetHierarchyRelationships(ds);
            }
            catch (Exception) { throw; }
            return ds;
        }
        //*----------------------------------------------------------*//
        public static void SetHierarchyRelationships(DataSet ds)
        {
            DataColumn fk;
            DataColumn[] pk = new DataColumn[1];
            ForeignKeyConstraint fkcdelete;
            DataRelation relation;
            string datarelationname = "ParentChild";
            try
            {
                ds.Tables[0].TableName = "Hierarchy";
                pk[0] = ds.Tables[0].Columns["NodeID"];
                fk = ds.Tables[0].Columns["ParentNodeID"];
                ds.Tables[0].PrimaryKey = pk;
                fkcdelete = new ForeignKeyConstraint(pk[0], fk);
                fkcdelete.DeleteRule = Rule.Cascade;
                relation = new DataRelation(datarelationname, pk[0], fk, false);
                ds.Tables[0].Constraints.Add(fkcdelete);
                ds.Tables[0].AcceptChanges();
                ds.Relations.Add(relation);
            }
            catch (Exception) { throw; }
            return;
        }
        //*----------------------------------------------------------*//
        public static bool CommitHierarchy(string connectionString, DataSet ds)
        {
            string sql = "";
            bool ret = false;
            int ModelID = 0;
            DataTable dt;
            try
            {
                if (ds.Tables.Count < 1) { return ret; }
                dt = ds.Tables[0];
                ModelID = int.Parse(dt.Rows[0]["ModelID"].ToString());
                sql = "select  * from Hierarchy where ModelID = " + ModelID.ToString();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].RowState.ToString() == "Deleted") { continue; }
                    if (int.Parse(dt.Rows[i]["ModelID"].ToString()) != ModelID)
                    {
                        dt.Rows[i]["ModelID"] = ModelID;
                    }
                }
                CommitToDataBase(connectionString, ds, sql);
                ret = true;
            }
            catch (Exception e)
            {
                //Debug.WriteLine(e.Message);
                throw;
            }
            return ret;
        }
        //*----------------------------------------------------------*//
        public static void CommitToDataBase(string connectionString, DataSet ds, string sql)
        {
            try
            {
                if (!ds.HasChanges()) { return; }
                using (OleDbConnection conn = new OleDbConnection())
                {
                    conn.ConnectionString = connectionString;
                    conn.Open();
                    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, conn))
                    {
                        OleDbCommandBuilder b = new OleDbCommandBuilder(da);
                        da.Update(ds.Tables[0]);
                        ds.AcceptChanges();
                    }
                }
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        public static DataSet GetDataSet(string connectionString, string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                using (OleDbConnection conn = new OleDbConnection())
                {
                    conn.ConnectionString = connectionString;
                    conn.Open();
                    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, conn))
                    {
                        da.Fill(ds);
                    }
                }
            }
            catch (Exception) { throw; }
            return ds;
        }        
        //*----------------------------------------------------------*//
        private void tvNotes_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                if (e.Label.Trim().Length < 1) { e.CancelEdit = true; }
                EditNode(tvNotes.SelectedNode, e.Label);
                tvNotes.SelectedNode.EndEdit(false);
                tvNotes.LabelEdit = false;
            }
            catch (Exception err) 
            { 
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void tbAccChan_Click(object sender, EventArgs e)
        {
            DataRow row = null;
            try
            {
                if (tvNotes.Nodes.Count == 0) { return; }
                row = (DataRow)tvNotes.Nodes[0].Tag;
                CommitHierarchy(DBConStr, row.Table.DataSet);
            }
            catch (Exception err)
            { 
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void InsertNewFolder(TreeNode node)
        {
         DataRow row = null;
         DataRow ParentRow = null;
         DataTable dt = null;
         int newindex = 0;
         try
         {
             ParentRow = (DataRow)node.Tag; 
             if (ParentRow == null) { return; }
             newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
             dt = ParentRow.Table;
             row = dt.NewRow();
             row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
			 row["NodeID"] = Guid.NewGuid().ToString();
			 row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
             row["Description"] = "New Node";
			 row["ImageIndex"] = 1;
			 row["SelectedImageIndex"] = 2;
             row["SortOrder"] = newindex;
             dt.Rows.Add(row);
             TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
             node.Nodes.Add(newNode);
             tvNotes.SelectedNode = newNode; 
         }
         catch (Exception) 
		 {
			 throw;
		 }

      }
        //*----------------------------------------------------------*//
        private void InsertNewItem(TreeNode node)
        {
            DataRow row = null;
            DataRow ParentRow = null;
            DataTable dt = null;
            int newindex = 0;
            try
            {
                ParentRow = (DataRow)node.Tag;
                if (ParentRow == null) { return; }
                newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
                dt = ParentRow.Table;
                row = dt.NewRow();
                row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
                row["NodeID"] = Guid.NewGuid().ToString();
                row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
                row["Description"] = "New Node";
                row["ImageIndex"] = 3;
                row["SelectedImageIndex"] = 3;
                row["SortOrder"] = newindex;
                dt.Rows.Add(row);
                TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
                node.Nodes.Add(newNode);
                tvNotes.SelectedNode = newNode;
            }
            catch (Exception)
            {
                throw;
            }

        }
       //*----------------------------------------------------------*//
        private void EditNode(TreeNode node, string newText)
        {
            DataRow row = null;
            try
            {
                if (node == null) { return; }
                if (node == tvNotes.Nodes[0]) { return; }
                row = (DataRow)node.Tag;
                if (row == null)
                {
                    return;
                }
                row["Description"] = newText;
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        public static void SetSelectedNodeByPosition(TreeView tv, int mouseX, int mouseY)
        {
            TreeNode node = null;
            try
            {
                Point pt = new Point(mouseX, mouseY);
                tv.PointToClient(pt);
                node = tv.GetNodeAt(pt);
                tv.SelectedNode = node;
                if (node == null) return;
                if (!node.Bounds.Contains(pt)) { return; }
            }
            catch { }
            return;
        }
        //*----------------------------------------------------------*//
        public static void LoadFromDataSet(TreeView tv, DataSet ds, string textColumnName)
        {
            TreeNode node;
            DataRow row;
            try
            {
                tv.Nodes.Clear();
                if (ds.Tables.Count < 1) { return; }
                if (ds.Tables[0].Rows.Count < 1) { return; }
                string fkcolumnname = FindForeignKeyColumnName(ds.Tables[0]);
                row = ds.Tables[0].Rows[0];
                tv.BeginUpdate();
                node = GetTreeNodeFromDataRow(row, textColumnName);
                tv.Nodes.Add(node);
                AddNodeFromDataRow(node, row, textColumnName, FindForeignKeyRelationName(row.Table));
            }
            catch (Exception) { throw; }
            finally
            {
                tv.EndUpdate();
                ds.AcceptChanges();
            }
        }
        //*----------------------------------------------------------*//
        public static void AddNodeFromDataRow(TreeNode parentNode, DataRow row, string textColumnName, string dataRelationName)
        {
            try
            {
                foreach (DataRow childrow in row.GetChildRows(dataRelationName))
                {
                    parentNode.Nodes.Add(GetTreeNodeFromDataRow(childrow, textColumnName));
                    AddNodeFromDataRow(parentNode.LastNode, childrow, textColumnName, dataRelationName);
                }
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        public static TreeNode GetTreeNodeFromDataRow(DataRow row, string textColumnName)
        {
            TreeNode child = null;
            string imageidx = "";
            string selimageidx = "";
            try
            {
                if (row.Table.Columns.Contains(ImageIndexColumnName))
                {
                    imageidx = row[ImageIndexColumnName].ToString();
                }
                if (row.Table.Columns.Contains(SelectedImageIndexColumnName))
                {
                    selimageidx = row[SelectedImageIndexColumnName].ToString();
                }
                child = new TreeNode();
                child.Text = row[textColumnName].ToString().Trim();
                if (imageidx.Length > 0)
                {
                    child.ImageIndex = Convert.ToInt32(imageidx);
                }
                if (selimageidx.Length > 0)
                {
                    child.SelectedImageIndex = Convert.ToInt32(selimageidx);
                }
                child.Tag = row;
            }
            catch (Exception) { throw; }
            return child;
        }
        //*----------------------------------------------------------*//
        public static void DeleteNode(TreeView tv)
        {
            DataRow row;
            try
            {
                if (tv.SelectedNode == null) { return; }
                if (tv.SelectedNode == tv.Nodes[0]) { return; }
                row = (DataRow)tv.SelectedNode.Tag;
                row.Delete();
                tv.SelectedNode.Remove();
            }
            catch (Exception) { throw; }
            return;
        }
        //*----------------------------------------------------------*//
        public static string FindForeignKeyColumnName(DataTable dt)
        {
            string Ret = "";
            try
            {
                DataSet ds = dt.DataSet;
                DataRelation rel = ds.Relations[0];
                Ret = rel.ChildColumns[0].ColumnName;
            }
            catch (Exception) { throw; }
            return Ret;
        }
        //*----------------------------------------------------------*//
        public static string FindForeignKeyRelationName(DataTable dt)
        {
            string Ret = "";
            try
            {
                DataSet ds = dt.DataSet;
                DataRelation rel = ds.Relations[0];
                Ret = rel.RelationName;
            }
            catch (Exception) { throw; }
            return Ret;
        }
        //*----------------------------------------------------------*// 
	}
}

Open in new window

0
Comment
Question by:peterkiers
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
14 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123495
The TreeViewEventArgs gives you access to the TreeNode, like this:

    this.TextBox1.Text = e.Node.Text;

Open in new window

0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123515
Hi,

This i found from another example, it's not quit right, but i think it gives the right direction:

 private void treeDB_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
       lblInfo.Text = DataClass.GetDisplayText((DataRow)e.Node.Tag);
    }

p.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123538
That would work, if you were storing an object in the TreeNode.Tag property.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 1

Author Comment

by:peterkiers
ID: 35123547
       private void tvNotes_AfterSelect(object sender, TreeViewEventArgs e)
        {

            DataRow row = null;
            textBox1.Text = (DataRow)tvNotes.Nodes[0].Tag;
        }

I get: Cannot implicitly convert type 'System.Data.DataRow' to 'string'      

P.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 35123562
If you are storing a DataRow in the Tag property, you can access a column value like this example:

DataRow row = e.Node.Tag as DataRow;
this.textBox1.Text = row["MyData"].ToString();

Open in new window

0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123602
Allthou i get no errors its not working...

Peter
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123629
Peter,

If what you have is not working, then I need more information.  Can you show me how you are creating TreeNodes?
0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123646
This is the way nodes a be created:

        private void tvSampleRightClickInsFolder(object sender, System.EventArgs e)
        {
            try
            {
                TreeNode node = tvNotes.SelectedNode;
                if ((node == null) || (node.ImageIndex == 3)) { return; }
                InsertNewFolder(node);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

private void InsertNewFolder(TreeNode node)
        {
         DataRow row = null;
         DataRow ParentRow = null;
         DataTable dt = null;
         int newindex = 0;
         try
         {
             ParentRow = (DataRow)node.Tag;
             if (ParentRow == null) { return; }
             newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
             dt = ParentRow.Table;
             row = dt.NewRow();
             row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
                   row["NodeID"] = Guid.NewGuid().ToString();
                   row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
             row["Description"] = "New Node";
                   row["ImageIndex"] = 1;
                   row["SelectedImageIndex"] = 2;
             row["SortOrder"] = newindex;
             dt.Rows.Add(row);
             TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
             node.Nodes.Add(newNode);
             tvNotes.SelectedNode = newNode;
         }
         catch (Exception)
             {
                   throw;
             }

      }

P.
0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123652
If I put data in de the column Data manually and start my application
the text will be shown in the texbox that is associated with the treeview
node. But the afterselect method does not work.

P.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35123656
Peter,

I see where you are creating a new TreeNode here:

 TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");

Open in new window


What I don't see is where you are setting the Tag property to the DataRow.  I would think you should have gotten an error accessing the TreeNode.Tag property, if it was null, unless you were looking at the wrong TreeNode.
0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123663
Sorry i forgot to mention a line that I have marked with an arrow.

P.
private void tvSampleRightClickInsFolder(object sender, System.EventArgs e)
        {
            try
            {
                TreeNode node = tvNotes.SelectedNode;
                if ((node == null) || (node.ImageIndex == 3)) { return; }
                InsertNewFolder(node);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

private void InsertNewFolder(TreeNode node)
        {
         DataRow row = null;
         DataRow ParentRow = null;
         DataTable dt = null;
         int newindex = 0;
         try
         {
             ParentRow = (DataRow)node.Tag; 
             if (ParentRow == null) { return; }
             newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
             dt = ParentRow.Table;
             row = dt.NewRow();
             row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
                   row["NodeID"] = Guid.NewGuid().ToString();
                   row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
             row["Description"] = "New Node";
                   row["ImageIndex"] = 1;
                   row["SelectedImageIndex"] = 2;
             row["SortOrder"] = newindex;
             row["Data"] = textBox1.Text; <===============================
             dt.Rows.Add(row);
             TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
             node.Nodes.Add(newNode);
             tvNotes.SelectedNode = newNode; 
         }
         catch (Exception) 
             {
                   throw;
             }

      }

P.

Open in new window

0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123670
In this methode the data of the treeview nodes will be saved to a database:

        private void tbAccChan_Click(object sender, EventArgs e)
        {
            DataRow row = null;
            try
            {
                if (tvNotes.Nodes.Count == 0) { return; }
                row = (DataRow)tvNotes.Nodes[0].Tag;
                CommitHierarchy(DBConStr, row.Table.DataSet);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
0
 
LVL 1

Author Comment

by:peterkiers
ID: 35123755
Wait a minute I think i am thinking wrong:

When I put the data manually into the column Data of the database
and i start my application, the code of the afterselect event works
because I see in the textbox the text that I have put in the database.
So the problem is not the afterselect-event.

But the event that inserts the node into the database. Because I
don't understand the code that well I don't know what is relevant
to show in the code-section so I have put it all.

I really hope someone can help me?
P.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DbTreeView
{
    public partial class MainForm : Form
    {
        private ContextMenu tvSampleMenu = new ContextMenu();
        private const string ImageIndexColumnName = "ImageIndex";
        private const string SelectedImageIndexColumnName = "SelectedImageIndex";
        private const string SortOrderColumnName = "SortOrder";
        private string DBName = "";
        private string DBConStr = "";

        public MainForm()
        {
            InitializeComponent();
        }
        //*----------------------------------------------------------*//
        private void MainForm_Load(object sender, EventArgs e)
	    {
         try
         {
        DBName = Application.StartupPath + @"\DBRoot.mdb";
        DBConStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";Data Source=" + DBName +";";
        tvSampleMenu.MenuItems.Add("Add Folder", new EventHandler(tvSampleRightClickInsFolder));
        tvSampleMenu.MenuItems.Add("Add Item", new EventHandler(tvSampleRightClickInsItem));
        tvSampleMenu.MenuItems.Add("Edit", new EventHandler(tvSampleRightClickEdit));
        tvSampleMenu.MenuItems.Add("Delete",new EventHandler(tvSampleRightClickDelete));
        LoadTree(tvNotes, GetHierarchy(DBConStr, 1));
           }
       catch (Exception err) 
         {  
           MessageBox.Show(err.Message);
         }
	    }
        //*----------------------------------------------------------*//
        private void LoadTree(TreeView tv, DataSet ds)
        {
            try
            {
                LoadFromDataSet(tv, ds, "Description");
                if (tv.Nodes.Count > 0)
                {
                    tv.Nodes[0].Expand();
                }
            }
            catch (Exception) 
            { 
                throw; 
            }
        }
        //*----------------------------------------------------------*//
        public static DataSet GetHierarchy(string connectionString, int modelID)
        {
            string sql = "";
            DataSet ds = null;
            try
            {
                sql = "select * from hierarchy ";
                sql += "  where modelid=" + modelID.ToString();
                sql += "  order by parentnodeid,sortorder asc";
                ds = GetDataSet(connectionString, sql);
                SetHierarchyRelationships(ds);
            }
            catch (Exception) { throw; }
            return ds;
        }
        //*----------------------------------------------------------*//
        public static void SetHierarchyRelationships(DataSet ds)
        {
            DataColumn fk;
            DataColumn[] pk = new DataColumn[1];
            ForeignKeyConstraint fkcdelete;
            DataRelation relation;
            string datarelationname = "ParentChild";
            try
            {
                ds.Tables[0].TableName = "Hierarchy";
                pk[0] = ds.Tables[0].Columns["NodeID"];
                fk = ds.Tables[0].Columns["ParentNodeID"];
                ds.Tables[0].PrimaryKey = pk;
                fkcdelete = new ForeignKeyConstraint(pk[0], fk);
                fkcdelete.DeleteRule = Rule.Cascade;
                relation = new DataRelation(datarelationname, pk[0], fk, false);
                ds.Tables[0].Constraints.Add(fkcdelete);
                ds.Tables[0].AcceptChanges();
                ds.Relations.Add(relation);
            }
            catch (Exception) { throw; }
            return;
        }
        //*----------------------------------------------------------*//
        public static bool CommitHierarchy(string connectionString, DataSet ds)
        {
            string sql = "";
            bool ret = false;
            int ModelID = 0;
            DataTable dt;
            try
            {
                if (ds.Tables.Count < 1) { return ret; }
                dt = ds.Tables[0];
                ModelID = int.Parse(dt.Rows[0]["ModelID"].ToString());
                sql = "select  * from Hierarchy where ModelID = " + ModelID.ToString();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].RowState.ToString() == "Deleted") { continue; }
                    if (int.Parse(dt.Rows[i]["ModelID"].ToString()) != ModelID)
                    {
                        dt.Rows[i]["ModelID"] = ModelID;
                    }
                }
                CommitToDataBase(connectionString, ds, sql);
                ret = true;
            }
            catch (Exception e)
            {
                //Debug.WriteLine(e.Message);
                throw;
            }
            return ret;
        }
        //*----------------------------------------------------------*//
        public static void CommitToDataBase(string connectionString, DataSet ds, string sql)
        {
            try
            {
                if (!ds.HasChanges()) { return; }
                using (OleDbConnection conn = new OleDbConnection())
                {
                    conn.ConnectionString = connectionString;
                    conn.Open();
                    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, conn))
                    {
                        OleDbCommandBuilder b = new OleDbCommandBuilder(da);
                        da.Update(ds.Tables[0]);
                        ds.AcceptChanges();
                    }
                }
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        public static DataSet GetDataSet(string connectionString, string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                using (OleDbConnection conn = new OleDbConnection())
                {
                    conn.ConnectionString = connectionString;
                    conn.Open();
                    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, conn))
                    {
                        da.Fill(ds);
                    }
                }
            }
            catch (Exception) { throw; }
            return ds;
        }        
        //*----------------------------------------------------------*//
        private void tvNotes_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            try
            {
                if (e.Label.Trim().Length < 1) { e.CancelEdit = true; }
                EditNode(tvNotes.SelectedNode, e.Label);
                tvNotes.SelectedNode.EndEdit(false);
                tvNotes.LabelEdit = false;
            }
            catch (Exception err) 
            { 
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void tbAccChan_Click(object sender, EventArgs e)
        {
            DataRow row = null;
            try
            {
                if (tvNotes.Nodes.Count == 0) { return; }
                row = (DataRow)tvNotes.Nodes[0].Tag;
                CommitHierarchy(DBConStr, row.Table.DataSet);
            }
            catch (Exception err)
            { 
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void InsertNewFolder(TreeNode node)
        {
         DataRow row = null;
         DataRow ParentRow = null;
         DataTable dt = null;
         int newindex = 0;
         try
         {
             ParentRow = (DataRow)node.Tag; 
             if (ParentRow == null) { return; }
             newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
             dt = ParentRow.Table;
             row = dt.NewRow();
             row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
			 row["NodeID"] = Guid.NewGuid().ToString();
			 row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
             row["Description"] = "New Node";
			 row["ImageIndex"] = 1;
			 row["SelectedImageIndex"] = 2;
             row["SortOrder"] = newindex;
             row["Data"] = textBox1.Text;
             dt.Rows.Add(row);
             TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
             node.Nodes.Add(newNode);
             tvNotes.SelectedNode = newNode; 
         }
         catch (Exception) 
		 {
			 throw;
		 }

      }
        //*----------------------------------------------------------*//
        private void InsertNewItem(TreeNode node)
        {
            DataRow row = null;
            DataRow ParentRow = null;
            DataTable dt = null;
            int newindex = 0;
            try
            {
                ParentRow = (DataRow)node.Tag;
                if (ParentRow == null) { return; }
                newindex = int.Parse(ParentRow["SortOrder"].ToString()) + 1;
                dt = ParentRow.Table;
                row = dt.NewRow();
                row["ModelID"] = int.Parse(ParentRow["ModelID"].ToString());
                row["NodeID"] = Guid.NewGuid().ToString();
                row["ParentNodeID"] = ParentRow[dt.PrimaryKey[0].ColumnName].ToString();
                row["Description"] = "New Node";
                row["ImageIndex"] = 3;
                row["SelectedImageIndex"] = 3;
                row["SortOrder"] = newindex;
                row["Data"] = textBox1.Text;
                dt.Rows.Add(row);
                TreeNode newNode = GetTreeNodeFromDataRow(row, "Description");
                node.Nodes.Add(newNode);
                tvNotes.SelectedNode = newNode;
            }
            catch (Exception)
            {
                throw;
            }

        }
       //*----------------------------------------------------------*//
        private void EditNode(TreeNode node, string newText)
        {
            DataRow row = null;
            try
            {
                if (node == null) { return; }
                if (node == tvNotes.Nodes[0]) { return; }
                row = (DataRow)node.Tag;
                if (row == null)
                {
                    return;
                }
                row["Description"] = newText;
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        private void tvSampleRightClickDelete(object sender, System.EventArgs e)
         {
         try
          {
		  DeleteNode(tvNotes);
          }
         catch 
             (Exception err) 
         { 
             MessageBox.Show(err.Message);
         }
         }
        //*----------------------------------------------------------*//
        private void tvSampleRightClickEdit(object sender, System.EventArgs e)
        {
            try
            {
                TreeNode node = tvNotes.SelectedNode;
                if (node == null) { return; }
                if (node == tvNotes.Nodes[0]) { return; }
                node.TreeView.LabelEdit = true;
                node.BeginEdit();
            }
            catch (Exception err) 
            { 
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void tvSampleRightClickInsFolder(object sender, System.EventArgs e)
        {
            try
            {
                TreeNode node = tvNotes.SelectedNode;
                if ((node == null) || (node.ImageIndex == 3)) { return; }
                InsertNewFolder(node);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void tvSampleRightClickInsItem(object sender, System.EventArgs e)
        {
            try
            {
                TreeNode node = tvNotes.SelectedNode;
                if (node == null) { return; }
                if ((node.ImageIndex == 0) || (node.ImageIndex == 3)) { return; }
                InsertNewItem(node);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        //*----------------------------------------------------------*//
        private void tvNotes_MouseDown(object sender, MouseEventArgs e)
        {
            SetSelectedNodeByPosition(tvNotes, e.X, e.Y);
            if (tvNotes.SelectedNode == null) { return; }
            if (e.Button == MouseButtons.Right) { return; }
        }
        //*----------------------------------------------------------*//
        private void tvNotes_MouseUp(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Right:
                    tvSampleMenu.Show(tvNotes, new Point(e.X, e.Y));
                    return;
                default:
                    break;
            }
        }
        //*----------------------------------------------------------*//
        public static void SetSelectedNodeByPosition(TreeView tv, int mouseX, int mouseY)
        {
            TreeNode node = null;
            try
            {
                Point pt = new Point(mouseX, mouseY);
                tv.PointToClient(pt);
                node = tv.GetNodeAt(pt);
                tv.SelectedNode = node;
                if (node == null) return;
                if (!node.Bounds.Contains(pt)) { return; }
            }
            catch { }
            return;
        }
        //*----------------------------------------------------------*//
        public static void LoadFromDataSet(TreeView tv, DataSet ds, string textColumnName)
        {
            TreeNode node;
            DataRow row;
            try
            {
                tv.Nodes.Clear();
                if (ds.Tables.Count < 1) { return; }
                if (ds.Tables[0].Rows.Count < 1) { return; }
                string fkcolumnname = FindForeignKeyColumnName(ds.Tables[0]);
                row = ds.Tables[0].Rows[0];
                tv.BeginUpdate();
                node = GetTreeNodeFromDataRow(row, textColumnName);
                tv.Nodes.Add(node);
                AddNodeFromDataRow(node, row, textColumnName, FindForeignKeyRelationName(row.Table));
            }
            catch (Exception) { throw; }
            finally
            {
                tv.EndUpdate();
                ds.AcceptChanges();
            }
        }
        //*----------------------------------------------------------*//
        public static void AddNodeFromDataRow(TreeNode parentNode, DataRow row, string textColumnName, string dataRelationName)
        {
            try
            {
                foreach (DataRow childrow in row.GetChildRows(dataRelationName))
                {
                    parentNode.Nodes.Add(GetTreeNodeFromDataRow(childrow, textColumnName));
                    AddNodeFromDataRow(parentNode.LastNode, childrow, textColumnName, dataRelationName);
                }
            }
            catch (Exception) { throw; }
        }
        //*----------------------------------------------------------*//
        public static TreeNode GetTreeNodeFromDataRow(DataRow row, string textColumnName)
        {
            TreeNode child = null;
            string imageidx = "";
            string selimageidx = "";
            try
            {
                if (row.Table.Columns.Contains(ImageIndexColumnName))
                {
                    imageidx = row[ImageIndexColumnName].ToString();
                }
                if (row.Table.Columns.Contains(SelectedImageIndexColumnName))
                {
                    selimageidx = row[SelectedImageIndexColumnName].ToString();
                }
                child = new TreeNode();
                child.Text = row[textColumnName].ToString().Trim();
                if (imageidx.Length > 0)
                {
                    child.ImageIndex = Convert.ToInt32(imageidx);
                }
                if (selimageidx.Length > 0)
                {
                    child.SelectedImageIndex = Convert.ToInt32(selimageidx);
                }
                child.Tag = row;
            }
            catch (Exception) { throw; }
            return child;
        }
        //*----------------------------------------------------------*//
        public static void DeleteNode(TreeView tv)
        {
            DataRow row;
            try
            {
                if (tv.SelectedNode == null) { return; }
                if (tv.SelectedNode == tv.Nodes[0]) { return; }
                row = (DataRow)tv.SelectedNode.Tag;
                row.Delete();
                tv.SelectedNode.Remove();
            }
            catch (Exception) { throw; }
            return;
        }
        //*----------------------------------------------------------*//
        public static string FindForeignKeyColumnName(DataTable dt)
        {
            string Ret = "";
            try
            {
                DataSet ds = dt.DataSet;
                DataRelation rel = ds.Relations[0];
                Ret = rel.ChildColumns[0].ColumnName;
            }
            catch (Exception) { throw; }
            return Ret;
        }
        //*----------------------------------------------------------*//
        public static string FindForeignKeyRelationName(DataTable dt)
        {
            string Ret = "";
            try
            {
                DataSet ds = dt.DataSet;
                DataRelation rel = ds.Relations[0];
                Ret = rel.RelationName;
            }
            catch (Exception) { throw; }
            return Ret;
        }
        //*----------------------------------------------------------*// 
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        private void tvNotes_AfterSelect(object sender, TreeViewEventArgs e)
        {
            DataRow row = e.Node.Tag as DataRow;
            this.textBox1.Text = row["Data"].ToString();
        }
        //*----------------------------------------------------------*// 
	}
}

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 35129295
Did you figure out your problem?
0

Featured Post

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question