Read data from DB to TreeView

Source: Internet
Author: User
There are two tables with the following structure:
Table province structure: province_id province_name (primary key: province_id)
Table city structure: city_id, city_name, province_id (primary key: city_id, province_id) SqlConnection conn = new SqlConnection ("server = Beijing; integrated security = sspi; database = test ");
SqlDataAdapter da;
DataSet ds = new DataSet ();
Private void Form1_Load (object sender, EventArgs e)
{
ReadNodes ();
This. treeView1.ExpandAll ();
}
Private void readNodes ()
{
String _ SQL = "select * from province ";
Da = new SqlDataAdapter (_ SQL, conn );
Da. Fill (ds, "province ");
DataView dvw1 = new DataView (ds. Tables ["province"]);
Int I = 0;
Foreach (DataRowView myRow1 in dvw1)
{
String strProvinceName = myRow1 ["province_name"]. ToString (). Trim ();
This. treeView1.Nodes. Add (new TreeNode (strProvinceName); // read ParentNode
// Certificate //---------------------------------------------------------------------------------------------------------------------------------------//
Da = new SqlDataAdapter ("select * from city where province_id = '" + myRow1 ["province_id"]. ToString (). Trim () + "'", conn );
Da. Fill (ds, "city ");
DataView dvw2 = new DataView (ds. Tables ["city"]);
Foreach (DataRowView myRow2 in dvw2)
{
String strCityName = myRow2 ["city_name"]. ToString (). Trim ();
This. treeView1.Nodes [I]. Nodes. Add (new TreeNode (strCityName); // read ChildNode
}
I ++;
Ds. Tables ["city"]. Clear ();
This. treeView1.SelectedNode = treeView1.Nodes [0];
}
}

The result is as follows:

Note: The TreeView shown in the code above only supports a 2-layer tree structure (related to the Table structure I tested). The method is relatively primitive, if you want to expand, you can use recursive calls to achieve node reading of the tree structure!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.