问题
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