Wednesday, 8 April 2015

ASP.NET - Create TreeView programmatically with CheckBoxes - ensure program can get checkbox value after postback

Watch this example on YouTube

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewCheckboxesPostBack.aspx.cs" Inherits="WebApplication1.TreeViewCheckboxesPostBack" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server" OnLoad="Panel1_Load"></asp:Panel>
    </div>
    </form>
</body>
</html>

CODE BEHIND

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class TreeViewCheckboxesPostBack : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Panel1_Load(object sender, EventArgs e)
        {
            TreeView tv = new TreeView();
            tv.ID = "MyID";
            tv.ShowCheckBoxes = TreeNodeTypes.All;
            for (int i = 0; i < 10; i++)
            {
                TreeNode tn = new TreeNode();
                tn.NavigateUrl = "Test " + i.ToString();
                tn.Text = "Test " + i.ToString();
                tn.ShowCheckBox = true;
                tv.Nodes.Add(tn);
            }
            Panel1.Controls.Add(tv);
            Button btn = new Button();
            btn.Text = "PostBack";
            btn.ID = "PostBack";
            btn.CausesValidation = false;
            btn.Click += (s, en) =>
                {
                    string checkBx = string.Empty;
                    foreach (TreeNode trN in tv.Nodes)
                    {
                        if (trN.Checked)
                        {
                            checkBx += trN.Value + ", ";
                        }
                    }
                    Session["CheckBoxes"] = checkBx;
                };
            Panel1.Controls.Add(btn);
        }
    }
}



No comments:

Post a Comment