ASP.NET: TreeView selection - SelectAction tip/trick
Q: I dont want my treeview control to postback if its SelectedNode not Changed. i mean; if you click over the selected item i dont want it to postback. how can i handle this. thanks for your help.
A: With code like this:
[VB]
''' <summary>
''' To store the path of last selected node
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private Property LastSelectedNodeValuePath() As String
Get
Dim ret As String = ""
If Not ViewState("LastSelectedNodeValuePath") Is Nothing Then
ret = ViewState("LastSelectedNodeValuePath")
End If
Return ret
End Get
Set(ByVal value As String)
ViewState("LastSelectedNodeValuePath") = value
End Set
End Property
Protected Sub TreeView1_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.SelectedNodeChanged
'Change the select action of the last selected node
If LastSelectedNodeValuePath <> "" Then
TreeView1.FindNode(LastSelectedNodeValuePath).SelectAction = TreeNodeSelectAction.Select
End If
'Set the current selected node
LastSelectedNodeValuePath = TreeView1.SelectedNode.ValuePath
'Set current selected node's select action
TreeView1.SelectedNode.SelectAction = TreeNodeSelectAction.None
End Sub
[C#]
private string LastSelectedNodeValuePath
{
get
{
string ret = "";
if (ViewState["LastSelectedNodeValuePath"] != null)
{
ret = ViewState["LastSelectedNodeValuePath"].ToString();
}
return ret;
}
set
{
ViewState["LastSelectedNodeValuePath"] = value;
}
}
protected void TreeView_cat_SelectedNodeChanged(object sender, EventArgs e)
{
//Change the select action of the last selected node
if (LastSelectedNodeValuePath != "")
{
TreeView1.FindNode(LastSelectedNodeValuePath).SelectAction = TreeNodeSelectAction.Select;
}
//Set the current selected node
LastSelectedNodeValuePath = TreeView1.SelectedNode.ValuePath;
//Set current selected node's select action
TreeView1.SelectedNode.SelectAction = TreeNodeSelectAction.None;
...
}