从RadTreeView获取选定的节点ID(从Sql Server填充)

时间:2018-10-08 14:13:35

标签: c# sql-server winforms radtreeview

我有一个TreeView,它从Sql Server表中获取数据。我的代码成功填充了父节点和子节点。 我只想知道选择任何节点时如何在文本框中获取该节点的ID。

  

ID列名称为:cabinetID

这是我用来填充TreeView的代码:

        public void loadContainerTree()
    {
       // fMain fm = new fMain();
       // txtRepositoryID.Text = fm.repositoryID.Text;
        repositoryid = Convert.ToInt32(txtRepositoryID.Text);

        conn.Open();
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tblCabinets WHERE ParentID IS NULL AND repositoryID = @RepositoryID", conn);
        adapter.SelectCommand.Parameters.AddWithValue("@RepositoryID", repositoryid);
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        RadTreeNode parentNode;
        foreach (DataRow dr in dt.Rows)
        {
            parentNode = ContainersTree.Nodes.Add(dr["CabinetName"].ToString());
            PopulateTreeView(dr["CabinetID"].ToString(), parentNode);
        }
        ContainersTree.ExpandAll();
        conn.Close();
    }

    private void PopulateTreeView(string parentid, RadTreeNode parentNode)
    {
        SqlDataAdapter adapterchild = new SqlDataAdapter("SELECT * FROM tblCabinets WHERE ParentID = @ParentID AND repositoryID = @RepositoryID", conn);
        adapterchild.SelectCommand.Parameters.AddWithValue("@ParentID", parentid);
        adapterchild.SelectCommand.Parameters.AddWithValue("@RepositoryID", repositoryid);
        DataTable dtchild = new DataTable();
        adapterchild.Fill(dtchild);

        foreach(DataRow dr in dtchild.Rows)
        {
            RadTreeNode childNode;
            if (parentNode == null)
            {
                childNode = ContainersTree.Nodes.Add(dr["cabinetName"].ToString());
            }
            else
            {

                childNode = parentNode.Nodes.Add(dr["cabinetName"].ToString());
                PopulateTreeView(dr["cabinetID"].ToString(), childNode);
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

带有TreeView/Tag或任何其他控件的基本工作流程。

首先Tag is an Object that contains data about the control. The default is null意味着我们可以使用标签存储stringint或任何CustomClass

现在让我们像这样创建Custom class

public class Cabinet
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Any other value
}

现在,我们将从数据库中获取数据并将其存储到树节点中,如下所示:

public static void AddNodeToTreeView(this TreeView tv, string Text, Cabinet cabinet)
{
    TreeNode n = new TreeNode();
    n.Text = Text;
    n.Tag = cabinet;
    tv.Add(n);
}

我们这样称呼:

Cabinet c = new Cabinet();
c.Id = 1;//You can store data from sql here
c.Name = "Some Name"; //You can store data from sql here
yourTreeView.AddNodeToTreeView("SomeTextTOBeDisplayed", c);

现在您需要做的就是从事件中获取所需的Node:

private void treeView1_Click(object sender, EventArgs e)
{
    Cabinet c = yourTreeView.SelectedNode.Tag as Cabinet;

    // Here do whatever you want with data
}

或from循环:

foreach(TreeNode n in yourTreeView.Nodes)
{
    Cabinet c = n.Tag as Cabinet;
}