开发环境是:vs2008 数据库是:Sql2008
数据库名字为:treeview。
表1名字:f_province
字段是province varchar(50)
表2名字:f_city
字段名字是:
city varchar(50)主键
province varchar(50)
在窗体中添加一个TreeView.以下是在load里面的代码:
先建一个类。命名为:dataCon
class dataCon
{
public static string strCon = "Data Source=localhost;Initial Catalog=treeview;Integrated security=SSPI;
//==================数据库连接===========================
public SqlConnection getcon()
{
SqlConnection sqlCon = new SqlConnection(strCon);
return sqlCon;
}
public static DataTable getDataTable(string sqlstr)//Dataset数据集
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (SqlConnection sqlcon = new SqlConnection(strCon))
{
using (SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon))
{
using (SqlDataAdapter sqlad = new SqlDataAdapter(sqlcom))
{
sqlad.Fill(ds);
dt = ds.Tables[0];
}
}
}
return dt;
}
}
在窗体中添加一个TreeView.以下是在load里面的代码:
private void Form5_Load(object sender, EventArgs e)
{
string strPro = "select province from f_province";//省份
DataTable dt = dataCon.getDataTable(strPro);
for (int i = 0; i < dt.Rows.Count; i++)
{
TreeNode RootNode = new TreeNode();
RootNode.Text = dt.Rows[i]["province"].ToString();
treeView1.Nodes.Add(RootNode);
string strCity = "select city from f_city where province='" + RootNode.Text+ "'";
//根据省份,取出城市
DataTable dtCity = dataCon.getDataTable(strCity);
for(int j=0;j<dtCity.Rows.Count;j++)
{
string ChildNode = dtCity.Rows[j]["city"].ToString();
RootNode.Nodes.Add(ChildNode);
}
}
}
已经试验过正常。