Web.config數據庫
在<configuration>中加入下面設置:app
<appSettings >
<add key="ConnectionString" value="server=localhost;database=db_06;user id=sa;password=''"/>
</appSettings>ide
DBClassurl
創建一個專門鏈接數據庫的類DBClassserver
public static SqlConnection GetConnection()
{
//獲取數據鏈接語句,並建立數據庫鏈接對象
String conn = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn;
myConn = new SqlConnection(conn);
return myConn;
}對象
下面建立一個GetUrl的方法:遞歸
public static string GetUrl(int filesId)
{
//得到url地址
SqlConnection myConnection = GetConnection();
SqlCommand myCommand = new SqlCommand("GetUrl", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
//添加參數
SqlParameter FilsesId = new SqlParameter("@FilesId", SqlDbType.Int, 4);
FilsesId.Value = filesId;
myCommand.Parameters.Add(FilsesId);
//添加參數
SqlParameter Url = new SqlParameter("@Url", SqlDbType.NVarChar, 100);
Url.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(Url);
//執行存儲過程
myConnection.Open();
myCommand.ExecuteNonQuery();
string url = Url.Value.ToString();
myCommand.Dispose();
myConnection.Dispose();
return url;
}string
後臺的鏈接數據庫代碼it
public DataSet CreateDataSet()
{
query = "select * from tbTree";
myAdapter = new SqlDataAdapter(query, myConn);
data = new DataSet();
myAdapter.Fill(data, "tree");
return data; io
}
頁面加載時的代碼
if (!IsPostBack)
{
//獲取數據鏈接語句,並建立數據庫鏈接對象
myConn = DBClass.GetConnection();
CreateDataSet();
InitTree(TreeView1.Nodes, "0");
}
一個遞歸顯示樹形結構
public void InitTree(TreeNodeCollection Nds, string parentId)
{
TreeNode NewNode;
//data爲存儲建樹數據信息的數據集
//用父節點進行篩選數據集中信息
DataRow[] rows = data.Tables[0].Select("parent_Id='" + parentId + "'");
foreach (DataRow row in rows)
{
NewNode = new TreeNode(row["title"].ToString(), row["Files_Id"].ToString(), row["NavigateUrl"].ToString()); Nds.Add(NewNode); InitTree(NewNode.ChildNodes, row["Files_Id"].ToString()); } }