Web.config
在<configuration>中加入下面设置:
<appSettings >
<add key="ConnectionString" value="server=localhost;database=db_06;user id=sa;password=''"/>
</appSettings>
DBClass
建立一个专门连接数据库的类DBClass
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;
}
后台的连接数据库代码
public DataSet CreateDataSet()
{
query = "select * from tbTree";
myAdapter = new SqlDataAdapter(query, myConn);
data = new DataSet();
myAdapter.Fill(data, "tree");
return data;
}
页面加载时的代码
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());
}
}