Asp.net TreeView to build recommended methods for user selection and Input

Source: Internet
Author: User

Generally, you can use the DropdownList control to select a single data item. However, it is best to use the TreeView control to implement multiple selective input and hierarchical input.

This article describes how to use the TreeView control to effectively obtain user input, it involves knowledge points such as cascade selection of the TreeView control, removing the HTML link of the node and changing it to expand directory, obtaining the selected content, constructing the database information into tree content, and using the pop-up window, in this article, I enter an application-level example, hoping to make a mark, which is good for others! Pai_^

The business scope of this article is a type of input and detailed sub-content. Due to the wide variety of content and a certain level of relationship, it is not suitable to use the DropdownList and CheckboxList controls, therefore, the TreeView control with the CheckBox attribute is used to assist in user input.

The input interface is roughly as follows. You can select a button to trigger the dialog box and place the TreeView control in the dialog box.

In the pop-up dialog box, the TreeView control is placed with a CheckBox to facilitate user selection and cascade (implemented through Javascript to reduce Post sending back). In addition, due to the large amount of content, I have set the level of expansion.

 

By selecting or selecting a category, you can select or reverse select all projects under the list, or select a sub-project separately.

 

 

Because Javascript is not very good at obtaining and assembling the returned content, this article uses the background traversal tree to process the returned value, and then binds the returned value in the Javascript of the parent form, display the content in the specified format in the interface control.

 

 

The following is the HTML code. OnTreeNodeChecked is a cascading Javascript function, and SubmitValue is the operation to bind the returned value.
Code
Copy codeThe Code is as follows:
<Div class = "search">
<Span>
<Asp: ImageButton ID = "btnSelect" runat = "server"
ImageUrl = "~ /Themes/Default/btn_select.gif "onclick =" btnSelect_Click"
/>
<Asp: ImageButton ID = "btnClose" runat = "server" OnClientClick = "javascript: window. close (); return false ;"
ImageUrl = "~ /Themes/Default/btn_close.gif "/>
</Span>
<Table cellspacing = "0" cellpadding = "0" border = "0" width = "100%">
<Tr>
<Td class = "ico">

</Td>
<Td class = "form">
<Asp: TreeView ID = "TreeView1" runat = "server" onclick = "OnTreeNodeChecked ();" ShowCheckBoxes = "All"
ShowLines = "True" ExpandDepth = "1" Font-Bold = "False" ForeColor = "# 0000CC">
</Asp: TreeView>
</Td>
</Tr>
</Table>
</Div>
<Script language = 'javascript 'Type = 'text/javascript '>
Function OnTreeNodeChecked (){
Var ele = event. srcElement;
If (ele. type = 'checkbox '){
Var childrenDivID = ele. id. replace ('checkbox', 'nodes ');
Var div = document. getElementById (childrenDivID );
If (div = null) return;
Var checkBoxs = div. getElementsByTagName ('input ');
For (var I = 0; I <checkBoxs. length; I ++ ){
If (checkBoxs [I]. type = 'checkbox ')
CheckBoxs [I]. checked = ele. checked;
}
}
}
Function SubmitValue (){
Var val = "";
Var returnVal = new Array ();
Var inputs = document. all. tags ("INPUT ");
Var n = 0;
For (var I = 0; I <inputs. length; I ++) // traverses all input values on the page
{
If (inputs [I]. type = "checkbox "){
If (inputs [I]. checked ){
Var strValue = inputs [I]. value;
Val + = strValue + ',';
// ReturnVal [n] = val;
N = n + 1;
}
} // If (inputs [I]. type = "checkbox ")
} //
Window. returnValue = val;
Window. close ();
}
</Script>

The following code is the background code of the page. It shows how to bind data to the tree so that it can display hierarchical content. AddTreeNode is a recursive function. The btnSelect_Click event processing function assembles the returned data and displays the data in the control input of the client in a certain format.
Code
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
If (! This. IsPostBack)
{
BindData ();
}
}
Private void BindData ()
{
ArrayList scopeTree = BLLFactory <businesssfactory>. Instance. GetTree ();
Foreach (BusinessScopeNodeInfo nodeInfo in scopeTree)
{
TreeNode node = new TreeNode (nodeInfo. Name );
Node. SelectAction = TreeNodeSelectAction. Expand;
This. TreeView1.Nodes. Add (node );
AddTreeNode (node, nodeInfo );
}
}
Private void AddTreeNode (TreeNode parentNode, BusinessScopeNodeInfo nodeInfo)
{
TreeNode treeNode = null;
Foreach (BusinessScopeNodeInfo subNodeInfo in nodeInfo. Children)
{
TreeNode = new TreeNode (subNodeInfo. Name );
TreeNode. SelectAction = TreeNodeSelectAction. Expand;
ParentNode. ChildNodes. Add (treeNode );
AddTreeNode (treeNode, subNodeInfo );
}
}
Protected void btnSelect_Click (object sender, ImageClickEventArgs e)
{
String result = "";
Foreach (TreeNode parent in this. TreeView1.Nodes)
{
Foreach (TreeNode node in parent. ChildNodes)
{
StringBuilder sb = new StringBuilder ();
Foreach (TreeNode subNode in node. ChildNodes)
{
If (subNode. Checked)
{
Sb. AppendFormat ("{0},", subNode. Text );
}
}
If (sb. Length> 0)
{
Sb. Insert (0, string. Format ("{0} (", node. Text ));
Sb. Append (")");
Result + = sb. ToString (). Replace (",)", ")") + ";";
}
Else if (node. Checked)
{
Result + = node. Text;
}
}
}
Helper. CloseWin (this, result. Trim (';'));
}

The data assembly of the number is also worth attention. To improve efficiency and avoid frequent queries to the database, we first put the qualified data into the DataTable, then, the Select object is searched in the memory, which can improve the efficiency of recursive functions.
Code
Copy codeThe Code is as follows:
/// <Summary>
/// Obtain the data tree
/// </Summary>
/// <Returns> </returns>
Public ArrayList GetTree ()
{
ArrayList arrReturn = new ArrayList ();
String SQL = string. Format ("Select * From {0} Order By PID, Seq", tableName );
Database db = DatabaseFactory. CreateDatabase ();
DbCommand cmdWrapper = db. GetSqlStringCommand (SQL );
DataSet ds = db. ExecuteDataSet (cmdWrapper );
If (ds. Tables. Count> 0)
{
DataTable dt = ds. Tables [0];
DataRow [] dataRows = dt. Select (string. Format ("PID = {0}",-1 ));
For (int I = 0; I <dataRows. Length; I ++)
{
Int id = Convert. ToInt32 (dataRows [I] ["ID"]);
BusinessScopeNodeInfo menuNodeInfo = GetNode (id, dt );
ArrReturn. Add (menuNodeInfo );
}
}
Return arrReturn;
}
Private BusinessScopeNodeInfo GetNode (int id, DataTable dt)
{
BusinessScopeInfo menuInfo = this. FindByID (id );
BusinessScopeNodeInfo menuNodeInfo = new BusinessScopeNodeInfo (menuInfo );
DataRow [] dChildRows = dt. Select (string. Format ("PID = {0}", id ));
For (int I = 0; I <dChildRows. Length; I ++)
{
Int childId = Convert. ToInt32 (dChildRows [I] ["ID"]);
BusinessScopeNodeInfo childNodeInfo = GetNode (childId, dt );
MenuNodeInfo. Children. Add (childNodeInfo );
}
Return menuNodeInfo;
}

The data entities used are shown in the following two classes. BusinessScopeNodeInfo is further encapsulated by the object BusinessScopeInfo to facilitate the provision of basic tree information, that is, BusinessScopeNodeInfo is an object that contains subclass data, businessScopeInfo is only the ing object of the database object.
Code
Copy codeThe Code is as follows:
/// <Summary>
/// Summary of BusinessScopeNodeInfo.
/// </Summary>
Public class BusinessScopeNodeInfo: BusinessScopeInfo
{
Private ArrayList m_Children = new ArrayList ();
/// <Summary>
/// Submenu object class object set
/// </Summary>
Public ArrayList Children
{
Get {return m_Children ;}
Set {m_Children = value ;}
}
Public BusinessScopeNodeInfo ()
{
This. m_Children = new ArrayList ();
}
Public BusinessScopeNodeInfo (BusinessScopeInfo scopeInfo)
{
Base. Id = scopeInfo. Id;
Base. Name = scopeInfo. Name;
Base. Seq = scopeInfo. Seq;
}
}

Code
Copy codeThe Code is as follows:
[Serializable]
Public class BusinessScopeInfo: BaseEntity
{
# Region Field Members
Private decimal m_Id = 0;
Private decimal m_Pid =-1;
Private string m_Name = "";
Private string m_Seq = "";
# Endregion
# Region Property Members
Public virtual decimal Id
{
Get
{
Return this. m_Id;
}
Set
{
This. m_Id = value;
}
}
Public virtual decimal Pid
{
Get
{
Return this. m_Pid;
}
Set
{
This. m_Pid = value;
}
}
Public virtual string Name
{
Get
{
Return this. m_Name;
}
Set
{
This. m_Name = value;
}
}
Public virtual string Seq
{
Get
{
Return this. m_Seq;
}
Set
{
This. m_Seq = value;
}
}
# Endregion
}

The data format is roughly as follows (this example works in the Oracle environment). In fact, the same is true for SqlServer or other databases.

Main research technologies: code generation tools and Secondary Development of Visio
Reprinted please indicate the source:
Written by: Wu huacong

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.