Reputation: 3736
I need to create a treeview control with checkboxes. However, my treeview needs to have checkboxes for the parent and the child. The business logic in my situation is that the user may choose "MS Office" but may not want "Microsoft".
I came across asp.net TreeView: how to use CheckBox in TreeView which helps, however, I can't seem to create a checkbox for "Microsoft" & "Adobe" nodes. How would I go about doing that?
The html code is:
<form id="form1" runat="server">
<div>
<h2 style="color:Green">TreeView: ShowCheckBoxes</h2>
<asp:Label
ID="Label1"
runat="server"
Text="Checked Favorite"
Font-Size="Medium"
ForeColor="SeaGreen"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:TreeView
ID="TreeView1"
runat="server"
DataSourceID="XmlDataSource1"
>
<DataBindings>
<asp:TreeNodeBinding DataMember="Products" Text="Products" />
<asp:TreeNodeBinding DataMember="Type" TextField="Name" />
<asp:TreeNodeBinding DataMember="Product" TextField="Name" ValueField="ID" />
</DataBindings>
</asp:TreeView>
<br />
<asp:XmlDataSource
ID="XmlDataSource1"
runat="server"
>
<Data>
<Products>
<Type Name="Microsoft">
<Product ID="1" Name="MS Office"/>
<Product ID="2" Name="ASP.NET"/>
</Type>
<Type Name="Adobe">
<Product ID="1" Name="ColdFusion"/>
<Product ID="2" Name="Flex"/>
<Product ID="2" Name="Photoshop"/>
</Type>
</Products>
</Data>
</asp:XmlDataSource>
<asp:Button ID="Button1" runat="server" Text="Submit Favorite" OnClick="Button1_Click" />
</div>
</form>
The code behind is:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace TreeviewCheckboxSample
{
public partial class Treeview : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your favorite:";
if (TreeView1.CheckedNodes.Count > 0)
{
foreach (TreeNode node in TreeView1.CheckedNodes)
{
Label1.Text += "<br />" + node.Text.ToString();
}
}
else
{
Label1.Text = "Checked before submit.";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;
TreeView1.ForeColor = System.Drawing.Color.Black;
TreeView1.BackColor = System.Drawing.Color.White;
TreeView1.Width = 200;
Button1.Font.Bold = true;
Button1.ForeColor = System.Drawing.Color.Crimson;
}
}
}
}
Upvotes: 1
Views: 5850
Reputation: 50104
The ShowCheckBoxes
property doesn't really cover this case.
However, you can change the ShowCheckBox
property on each individual node after the tree is bound. That page contains some example code that even does it based on the node's depth, which looks like what you're after.
Upvotes: 2