asp.net 2.0 to implement the Treeview binding with the database (with code)
Programming Ideas:
Each record represents a node. The logical hierarchical relationship is formed by the F_nodeid and F_parentnodeid of the 2 digital core fields in the table. The contract 0 represents the root node. Other fields are secondary fields and are not related to this article.
Define and initialize an object array mynodes, and then read the records in the table at once, establishing all the subordinate relationships by determining the parent node of the current node.
Sample data:
Run Result:
Sample Downloads: Http://www.why100000.com/_ftps/samples/Tree+db.rar
(Code Debugging Environment: Visual Web Developer, Edition Express)
Access database name: Db_system.mdb
Table Name: TabItems
Table structure:
F_i_autoid Automatic Numbering
F_nodeid number (this node ID)
F_parentnodeid Number (parent node ID)
F_name text
F_tag text
F_url text
F_order Digital
F_ishidden text
F_datetime Date/Time
Key code:
Using System;
Using System.Data;
Using System.Data.OleDb;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
String sDBPath = "./db_system.mdb"; //"
String spassword = "";
String sdbtable = "TabItems";
OleDbConnection oconn = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Server.MapPath (SDbPath) + "; Password= "+ Spassword +"; ");
OleDbDataReader oDr;
Try
{
oConn.Open ();
OleDbCommand ocmd = new OleDbCommand ("SELECT * from" + sdbtable, oconn); + "ORDER by F_level"
ODr = Ocmd.executereader ();
Defining an array of objects
treenode[] Mynodes = new treenode[100];
Initializing an array of objects
for (int i = 0; i < mynodes.length; i++)
{
Mynodes[i] = new TreeNode ();
}
Fetching data from a table
while (Odr.read ())
{
int iparentnodeid = (int) odr["F_parentnodeid"];
int imynodeid = (int) odr["F_nodeid"];
if (Iparentnodeid!= 0)
{
Mynodes[imynodeid]. Text = odr["F_name"]. ToString ();
Mynodes[imynodeid]. NavigateUrl = odr["F_url"]. ToString ();
Mynodes[iparentnodeid]. Childnodes.add (Mynodes[imynodeid]);
}
Else
{
Mynodes[imynodeid]. Text = odr["F_name"]. ToString ();
Mynodes[imynodeid]. SelectAction = Treenodeselectaction.none;
TREEVIEW1.NODES.ADD (Mynodes[imynodeid]);
}
}
}
catch (System.Exception Sqle)
{
Sqle. ToString (). Replace ("n", "<br>");
Response.Write (Sqle);
}
Finally
{
Oconn.close ();
}
}
}
}
-------------------------------------------------------
My other articles are on my personal website:
"100,000 Why" computer Learning Network: http://www.why100000.com
Zhang Qing zhangking@hotmail.com,qq:9365822
http://why100000.com
http://sogo99.com
2006.1.10