我使用下面的代码将新类别添加到dataBase中的categories表中 但selectedNode的返回值始终为null。 有什么问题?
protected void btnAddNode_Click(object sender, EventArgs e)
{
string selectedNodeValue = CategoryTreeView.SelectedNode.Value;
using (mydbEntities context = new mydbEntities())
{
int id = Int32.Parse(selectedNodeValue);
Category obj = new Category();
obj.Name = "bla bla";
obj.CategoryParentId_FK = id;
context.Categories.AddObject(obj);
context.SaveChanges();
}
bindTreeView();
}
还有一件事,我的categorytreeview在更新面板中
这是我的标记
<div id="MyTreeDiv" class="TreeContiner">
<asp:TreeView ID="CategoryTreeView" runat="server" ShowLines="true"
LineImagesFolder="images/treeRTLlines" CssClass="AspNet-TreeView"
onselectednodechanged="CategoryTreeView_SelectedNodeChanged">
<NodeStyle CssClass="AspNet-TreeView-Nodes" />
<SelectedNodeStyle CssClass="AspNet-TreeView-Selected-Nodes" />
</asp:TreeView>
<div class="treeTools">
<asp:LinkButton ID="btnAddNode" runat="server" CausesValidation="False"
CssClass="treeToolsLnk"
Text="" onclick="btnAddNode_Click"><img src="Images/refresh.png" /></asp:LinkButton>
这是我的bindtreeview方法
#region bindTreeView
private void bindTreeView()
{
CategoryTreeView.Nodes.Clear();
using (mydbEntities context = new mydbEntities())
{
var parents = context.Categories.Where(a => a.CategoryParentId_FK == null).OrderBy(a => a.Name);
if (parents.Any())
{
foreach (var p in parents)
{
TreeNode root = new TreeNode(p.Name, p.Id.ToString());
root.SelectAction = TreeNodeSelectAction.Select;
CreateNode(root);
CategoryTreeView.Nodes.Add(root);
}
}
}
}
void CreateNode(TreeNode node)
{
using (mydbEntities context = new mydbEntities())
{
int p = Int32.Parse(node.Value.ToString());
var childrens = context.Categories.Where(a => a.CategoryParentId_FK == p).OrderBy(a => a.Name);
if (childrens.Any())
{
foreach (var c in childrens)
{
TreeNode tnode = new TreeNode(c.Name, c.Id.ToString());
tnode.SelectAction = TreeNodeSelectAction.Select;
node.ChildNodes.Add(tnode);
CreateNode(tnode);
}
}
}
}
#endregion
答案 0 :(得分:0)
似乎您想要获取所选节点的值。 这样做的方法是使用SelectedNodeChanged。
<asp:TreeView id="CategoryTreeView"
Font-Names= "Arial"
ForeColor="Blue"
SelectedNodeStyle-ForeColor="Green"
SelectedNodeStyle-VerticalPadding="0"
OnSelectedNodeChanged="Select_Change"
runat="server">
CS:
void Select_Change(Object sender, EventArgs e)
{
string selectedNodeValue = CategoryTreeView.SelectedNode.Value;
using (mydbEntities context = new mydbEntities())
{
int id = Int32.Parse(selectedNodeValue);
Category obj = new Category();
obj.Name = "bla bla";
obj.CategoryParentId_FK = id;
context.Categories.AddObject(obj);
context.SaveChanges();
}
bindTreeView();
}