c# - 动态填充 TreeView... 像类别 > 父类别
问题描述
在这里,我编写了一些代码来获取 TreeView 中的类别,例如 --Core ---Core Subcat --Non Core ---Non Core Subcat
我的代码只显示:
- 核
- 非核心
请帮我解决这个代码。如果我错了,请纠正我。
谢谢你。
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);
private void btnLoadNodes_Click(object sender, EventArgs e)
{
DataTable dt = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =0");
this.PopulateTree(dt, 0, null);
}
private void PopulateTree(DataTable dtParent, int parentId, TreeNode treeNode)
{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["Cat_Name"].ToString(),
Tag = row["Cat_ID"]
};
if (parentId == 0)
{
treeViewCat.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat="+ child.Tag);
}
else
{
treeNode.Nodes.Add(child);
}
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
TreeView 中的预期结果:
-Core
--Core Subcat
-Non Core
--Non Core Subcat
解决方案
我认为最好更改“Sql Select”。如果您在TreeView模型中获取数据,则可以非常简单地显示它。
在此示例中,“rn”字段将对您有很大帮助。
推荐阅读
- angular - Angular:通过实例化组件访问 DOM
- typescript - 将量角器命令行参数作为变量传递
- asp.net - 在 VS 2012 中调试我的 asp.net mvc 将返回此错误“HTTP Error 500.0 - Internal Server Error”
- php - 登录身份验证系统在PHP中不起作用
- java - 两个MappedSuperClass对象报错:这个类没有定义一个IdClass
- python - 从python中的数组列表中制作所有数组
- html - 如何使h2移动响应?
- javascript - 如何在javascript中使用输入文本的值
- c# - 更改角色授权以返回自定义错误而不是重定向
- javascript - 使用 jQuery 在基于另一个类的另一个 div 中添加一个类