Bind C# Windows Form TreeView from DataBase

我怕爱的太早我们不能终老 提交于 2020-01-25 10:05:30

问题


My DataBase Table Structure is like this :

ID(Primary Key ) , Title (Nvarchar) , ParentID (this is the ID of current table)

and the 'ParentID' of first node (root) is valued = -1 i loaded this data in Memory.(for example in a list of class) how can i add the items with a loop or something else to TreeView ?


回答1:


Just order your data by ParentID, first results will be root one (-1). Then use

        if (ParentID == -1)
        {
            treeView1.Nodes.Add(ID, Title);
        }
        else
        {
           TreeNode tn = treeView1.Nodes.Find(ID, true)[0];
           tn.Nodes.Add(ID, Title);
        }

thats how u make sure all previous nodes will be already in tree, and find them by unique key (ID).




回答2:


You can loop over data and create TreeNodes that contains the data you want to display. You can also parent the nodes as you see fit (if needed).

You can then add the treenodes to the treeview's node collection.




回答3:


I did wrote this code :

  private void Heading_Load(object sender, System.EventArgs e)
{
    InsertNodes(null, 0);
}
private void InsertNodes(TreeNode n, int hdrID)
{
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=Acounting;Integrated Security=True;Pooling=False");
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT hdrid,title FROM [Heading] WHERE ParentID=" + hdrID, con);
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read()) {
        TreeNode t = new TreeNode(rdr("title").ToString());
        InsertNodes(t, Convert.ToInt16(rdr("hdrID").ToString()));
        if (n == null) {
            trvHeader.Nodes.Add(t);
        } else {
            n.Nodes.Add(t);
        }
    }
    rdr.Close();
         }

how is it?



来源:https://stackoverflow.com/questions/5181371/bind-c-sharp-windows-form-treeview-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!