[英]Recursion SQL to TreeView C# ASP.NET
我有以下存储过程:
ALTER PROCEDURE [dbo].[sp_AssetRegisterTreeGet]
(@AssetID INT)
AS
BEGIN
SET NOCOUNT ON;
WITH results AS
(
SELECT
AssetID, ParentAssetID, AssetNumber
FROM
T_AssetRegister
WHERE
AssetID = @AssetID
UNION ALL
SELECT
t.AssetID, t.ParentAssetID, t.AssetNumber
FROM
T_AssetRegister t
INNER JOIN
results r ON r.ParentAssetID = t.AssetID
)
SELECT *
FROM results
ORDER BY AssetID
OPTION (maxrecursion 0);
END
结果看起来像这样:
AssetID ParentAssetID AssetNumber
----------------------------------------------
1 NULL root
2 1 Group
3 2 Group - A
如何使用C#使用上述存储过程将其加载到ASP.NET中的<asp:TreeView>
中?
我得到了答案:
DataTable dtTree = new DataTable();
public void CollTree()
{
using (SqlConnection conn = new SqlConnection((ConfigurationManager.ConnectionStrings["sconn"].ConnectionString)))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AssetRegisterTreeGet";
cmd.Parameters.Add("@AssetID", SqlDbType.Int).Value = Request.QueryString["Id"].ToString();
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTree);
da.Dispose();
cmd.Dispose();
conn.Dispose();
}
AddNodes(-2147483648, TreeView1.Nodes);
}
void AddNodes(int id, TreeNodeCollection tn)
{
foreach (DataRow dr in dtTree.Select("ParentAssetID = " + id))
{
TreeNode sub = new TreeNode(dr["AssetNumber"].ToString(), dr["AssetID"].ToString());
tn.Add(sub);
AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);
}
}
其中-2147483648
是根ID。
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.