当前位置:编程问答 > C#/ASP.NET >

C#中TreeView与数据库绑定?

问题:请个高手教一下TreeView从数据库中读取数据的过程.我在搞一个类似于QQ的软件,我怎么把数据库中好友表的数据绑定到TreeView里面.并且右键能打开对好友资料的查询.请高手写下代码,最好有注释的.谢谢!或者加QQ:306057261 找位老师具体讲解下!
答案:
自己写的个操作数据库类dbClass.cs放在App_Code文件: 
using System;
using System.Data;
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;
using System.Data.SqlClient;
/// <summary>
/// dbClass 的摘要说明
/// </summary>
public class dbClass
{
public SqlConnection MyConn;
public SqlCommand MyComm;
public SqlDataAdapter myAdapter;
public SqlDataReader myReader;
public SqlCommandBuilder myCommandBuilder;
public DataSet ds;
public DataTable dt;
public DataRow dr;
public dbClass()
{
//
// TODO: 在此处添加构造函数逻辑
//
MyConn = new SqlConnection("Data Source=.;Initial Catalog=tree;Persist Security Info=True;User ID=sa;Password=;");
}
//连接数据库
public void Open()
{
MyConn = new SqlConnection("Data Source=.;Initial Catalog=tree;Persist Security Info=True;User ID=sa;Password=;");
if (MyConn.State.ToString() != "Open")
MyConn.Open();
}
public void Close()
{
if (ds != null)
{
ds.Dispose();
}
if (MyConn != null & MyConn.State.ToString() != "Closed")
{
MyConn.Close();
}
}
//对数据库的添加,修改,删除等操作
public void OpSql(string sqlstr)
{
this.Open();
MyComm = new SqlCommand(sqlstr, MyConn);
MyComm.ExecuteNonQuery();
MyComm.Dispose();
this.Close();
}
}
往Menu.aspx文件里拖一个TreeView控件
Menu.aspx.cs文件:
using System;
using System.Data;
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;
using System.Data.SqlClient;
public partial class Menu : System.Web.UI.Page
{
dbClass db = new dbClass();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
db.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from tree", db.MyConn);
DataSet ds = new DataSet();
adp.Fill(ds);
db.Close();
AddTree((TreeNode)null, ds);
}
}
public void AddTree( TreeNode pNode,DataSet ds)
{
DataTable dvTree = ds.Tables[0];
DataRow[] dr = dvTree.Select("[Pid] = [id]");
foreach (DataRow Row in dr)
{
TreeNode Node = new TreeNode();
Node.Text = Row["TreeName"].ToString();
TreeView1.Nodes.Add(Node);
AddNodes(Row["id"].ToString(), Node, dvTree);
}
}
public void AddNodes(string ParentID, TreeNode pNode, DataTable dvTree)
{
DataRow[] dr = dvTree.Select("[Pid] = " + ParentID + "and [Pid] <> [id]");
foreach (DataRow Row in dr)
{
TreeNode Node = new TreeNode();
Node.Text = Row["TreeName"].ToString();
pNode.ChildNodes.Add(Node);
AddNodes(Row["id"].ToString(), Node, dvTree);
}
}
}
好友和TreeView绑定???
为什么不是ListView呢??
先将数据绑定到TreeNode中再先treenode绑定到treeview中
很简单的。你研究下TreeNode就可以了。

上一个:寻找c#对access操作的示例
下一个:姹備釜锛欳#鐧婚檰楠岃瘉浠g爜 - 宸茶В鍐?- 鎼滄悳闂棶

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,