This is a migrated thread and some comments may be shown as answers.

Clearing Custom Text Box when Node Unchecked

4 Answers 65 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
Jon Ingersoll
Top achievements
Rank 1
Jon Ingersoll asked on 18 Aug 2011, 06:23 PM
I've created a usercontrol that allows users to select "interests" using a RadTreeView so that it can expand and display a hierachy.

In the node template I added in a text box for users to type in a free response if they choose certain fields. It's all working beautifually, with one gotcha.  If a user unchecks the box, the text is still display until

1) the refresh the page
2) I databind the tree

Each of those are not overly desirable solutions, 1) being confusing to the user, 2) loses the state of any expanded nodes.

As the textboxes are created dynamically, they don't have ID's that I could reference with a FindControl and clear them when the appropriate check box is unclicked.

Any thoughts?

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Engage20.ascx.cs" Inherits="edu.yale.som.engage.Engage20" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<style type="text/css">
    .rootNode
    {
        font-size: 13px;
        font-weight: bold;
    
     
    div[class='rtTop rtSelected'] div.rtIn,
    div[class='rtMid rtSelected'] div.rtIn,
    div[class='rtBot rtSelected'] div.rtIn
    {
        color: black !important;
        background-color: transparent !important;
        background-image: none !important;
        border-color: transparent !important;
    }
 
</style>
<script type="text/javascript">
 
    function TreeView_OnClientLoad() {
        var $ = $telerik.$;
        $(".rtTemplate").bind("keydown", function (e) {
            if (e.keyCode == 32)
                e.stopPropagation();
        });
 
    }
 
    function OnClientNodeChecked(sender, eventArgs) {
 
        var node = eventArgs.get_node();
        if (node.get_allowEdit() && node.get_checked()) {
            node.select();
        }
}
 
 
 
</script>
<table border="0" width="100%"><tr><td>
 
 
<telerik:RadTreeView ID="EngageTree" runat="server" CheckBoxes="true" DataFieldID="TagID"
    DataFieldParentID="ParentID" DataTextField="Name" DataSourceID="TagDataSource"
    Skin="Vista" OnNodeCheck="OnNodeChecked" DataValueField="TagID" EnableViewState="true" OnClientLoad="TreeView_OnClientLoad" OnClientNodeChecked="OnClientNodeChecked">
    <DataBindings>
        <telerik:RadTreeNodeBinding Depth="0" CheckableField="Checkable" TextField="Name" Expanded="False"
            CssClass="rootNode" CheckedField="Checked" AllowEditField="IncludeTextBox" CategoryField="UserResponse"/>
        <telerik:RadTreeNodeBinding CheckedField="Checked" AllowEditField="IncludeTextBox" CheckableField="Checkable" CategoryField="UserResponse"/>
    </DataBindings>
    <NodeTemplate>
        <%# DataBinder.Eval(Container, "Text") %> <asp:TextBox Text='<%# DataBinder.Eval(Container, "Category") %>' ToolTip='<%# DataBinder.Eval(Container, "Value") %>' runat="server" Visible='<%# DataBinder.Eval(Container, "AllowEdit").ToString() == "True" %>' AutoPostBack="true" OnTextChanged="textBox_OnTextChanged" />
    </NodeTemplate>
</telerik:RadTreeView></td>
<td>
 <asp:Panel ID="EngageTextResponses" runat="server">
 </asp:Panel>
</td>
</tr></table>
 
<asp:SqlDataSource ID="TagDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:edu_yale_som_engage_connectionString %>"
    SelectCommand="SELECT Tags.TagID, Tags.ParentID, Tags.Name, Tags.Description, Tags.Checkable, Tags.IncludeTextBox, Tags.TypeID, Tags.AssociatedAction, Tags.Position, UserTags.PersonID, UserTags.UserResponse, Tags.IncludeTextBox,
 CASE When PersonID IS NULL Then 'false' Else 'true' END As Checked
 FROM Tags LEFT OUTER JOIN (SELECT RecordID, TagID, PersonID, DateStamp, UserResponse
 FROM UserTags AS UserTags_1
   WHERE (PersonID = @PersonID)) AS UserTags ON Tags.TagID = UserTags.TagID
 WHERE (Tags.TypeID = @TypeID) Order By Position ASC, Tags.Name ASC">
 <SelectParameters>
    <asp:ControlParameter ControlID="HiddenFieldPersonID" PropertyName="Value" Name="PersonID" />
    <asp:ControlParameter ControlID="HiddenFieldTypeID" PropertyName="Value" Name="TypeID" />
 </SelectParameters>
 </asp:SqlDataSource>
 
 <asp:HiddenField ID="HiddenFieldPersonID" runat="server" />
 <asp:HiddenField ID="HiddenFieldTypeID" runat="server" />

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
 
namespace edu.yale.som.engage
{
    public partial class Engage20 : System.Web.UI.UserControl
    {
 
        public edu.yale.som.sitefinity.shared.Common commonCode = null;
        private String connectionStringName = null;
        SqlConnection dbConn = null;
        public int personID;
 
        private String _TagTypeID = null;
 
        public string TagTypeID
        {
            get
            {
                return ViewState["_TagTypeID"] as String;
            }
            set
            {
                try
                {
                    //check if page is being accessed in the admin
                    if (commonCode.IsPageInAdmin(this))
                    {
                        //check if the users is an admin
                        if (!Page.User.IsInRole("Admins"))
                        {
                            throw new Exception("Unauthorized access attempt!");
                        }
                    }
                    ViewState["_TagTypeID"] = value;
                }
                catch (Exception e)
                {
                    throw new Exception("Error in edu.yale.som.engage.Engage20.SetTagTypeID()" + e.Message);
                }
            }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
            //check to see if property is set.
            if (TagTypeID == null || TagTypeID == string.Empty || TagTypeID == "")
            {
                throw new Exception("Tag Type not set");
            }
            try
            {
                // Retrieve the Person ID for the current user
                personID = commonCode.getPersonID(commonCode.RealmNameStripper(Page.User.Identity.Name, HttpContext.Current), commonCode.getSessionAuthenticationImplementationID(HttpContext.Current));
                //set PersonID and TagTypeID values into the front end controls for the DataSource to use.
                HiddenFieldPersonID.Value = personID.ToString();
                HiddenFieldTypeID.Value = TagTypeID;
                 
            }
            catch (Exception ex)
            {
                throw new Exception("Error in edu.yale.som.engage.Engage20.Page_Load(): " + ex.Message);
            }
             
        }
 
 
        public Engage20()
        {
            try
            {
                // Initalize the common object
                commonCode = new edu.yale.som.sitefinity.shared.Common();
                // Initialize the connection string name for connecting to Engage            
                if (ConfigurationManager.ConnectionStrings["edu_yale_som_engage_connectionString"] == null || ConfigurationManager.ConnectionStrings["edu_yale_som_engage_connectionString"].ToString() == string.Empty)
                {
                    throw new Exception("Invalid database connection string.");
                }
 
                connectionStringName = ConfigurationManager.ConnectionStrings["edu_yale_som_engage_connectionString"].ToString();
 
            }
            catch (Exception ex)
            {
                throw new Exception("Error in edu.yale.som.engage.Engage20 constructor: " + ex.Message);
            }
        }
 
        protected void OnNodeChecked(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        {
            dbConn = new SqlConnection(connectionStringName);
 
            if (e.Node.Checked)
            {
                try
                {
                    // Open the database connection
 
                    dbConn.Open();
                    string t = e.Node.Value.ToString();
                    string InsQuery = "IF NOT EXISTS (SELECT * FROM UserTags WHERE tagID = " + @t + " AND personID = " + @personID + ") INSERT into UserTags(TagID, PersonID) VALUES(" + @t + "," + @personID + ")";
                    SqlCommand dbCmd = new SqlCommand(InsQuery, dbConn);
                    dbCmd.ExecuteNonQuery();
 
                }
                catch (Exception ex)
                {
                    throw new Exception("Error Inserting User Tags edu.yale.som.engage.Engage20.OnNodeChecked() '" + ex.Message);
                }
                finally
                {
 
                    if (dbConn != null)
                    {
                        dbConn.Close();
                    }
                }
 
            }
            else
            {
                try
                {
                    // Open the database connection
 
                    dbConn.Open();
                    string t = e.Node.Value.ToString();
                    string Query = "DELETE FROM UserTags WHERE tagID = " + @t + " AND personID = " + @personID;
                    SqlCommand dbCmd = new SqlCommand(Query, dbConn);
                    dbCmd.ExecuteNonQuery();
                    /*
                    if (e.Node.AllowEdit){
                        EngageTree.DataBind();
                    }
                    */
                }
                catch (Exception ex)
                {
                    throw new Exception("Error Deleting User Tags edu.yale.som.engage.Engage20.textBox_OnTextChanged() '" + ex.Message);
                }
                finally
                {
 
                    if (dbConn != null)
                    {
                        dbConn.Close();
                    }
                }
 
            }
 
 
        }
 
        protected void textBox_OnTextChanged(object sender, EventArgs e)
        {
            TextBox box = (TextBox)sender;
            string InsQuery = null;
            string t = string.Empty;
 
            try
            {
                // Open the database connection
                dbConn = new SqlConnection(connectionStringName);
                dbConn.Open();
                t = box.ToolTip.ToString();
                InsQuery = "IF EXISTS (SELECT * FROM UserTags WHERE tagID = " + @t + " AND personID =" + @personID + ") UPDATE UserTags SET UserResponse = '" + box.Text + "' WHERE tagID = " + @t + " AND personID =" + @personID + " ELSE INSERT into UserTags(TagID, PersonID, UserResponse) VALUES(" + @t + "," + @personID + ",'" + box.Text + "' )";
                SqlCommand dbCmd = new SqlCommand(InsQuery, dbConn);
                dbCmd.ExecuteNonQuery();
 
            }
            catch (Exception ex)
            {
                throw new Exception("Error Inserting User Tags edu.yale.som.engage.Engage20.OnTextChanged() " + ex.Message);
            }
            finally
            {
 
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
        }
    }
}

4 Answers, 1 is accepted

Sort by
0
Plamen
Telerik team
answered on 23 Aug 2011, 05:52 PM
Hi Jon,

Could you clarify what excatly is the behavior that you are trying to implement. In case you want to clear the text of the template textbox when a check box is unchecked you could subscribe on the client-side OnClientNodeChecked event of the RadTreeView and use the following implementation of the event handler function:
function OnClientNodeChecked(sender, args) {
 
                if (!args.get_node().get_checked()) {
                     
                   
                    $telerik.$(":input[type=text]", args.get_node().get_element()).attr("value","");
                    
                }
            }

In case this is not he desired functionality, try to provide more information.

Kind regards,
Plamen Zdravkov
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

0
Jon Ingersoll
Top achievements
Rank 1
answered on 23 Aug 2011, 06:50 PM
Plamen,

Thank you for the response. Yes, what I am trying to do is clear the template text box when the check box in it's node is unchecked. I already had code for OnClientNodeChecked, that selects the node when the checkbox is selected. It's there to solve an odd issue that when the node is not selected the ontextchange event of the text box wasn't fire.

I added your code at first I thought it was wrong, but I realized that there was a name mismatch between my code and yours. After that, it worked like a charm. Thanks! Here is the updated code:

function OnClientNodeChecked(sender, eventArgs) {
 
        var node = eventArgs.get_node();
        if (node.get_allowEdit() && node.get_checked()) {
            node.select();
        } if (!node.get_checked()) {
            $telerik.$(":input[type=text]", node.get_element()).attr("value", "");
        }
         
    }


0
Jon Ingersoll
Top achievements
Rank 1
answered on 21 Oct 2011, 05:11 PM
Oops, it appears I spoke too soon.

Yes, this code does blank out the text when the checkbox related to it is unchecked. It however ALSO blanks it if the parent node of that checkbox is unchecked.
0
Plamen
Telerik team
answered on 25 Oct 2011, 04:07 PM
Hello Jon,

You can try to change the jquery selector so that it takes only the first input: ":input[type=text]:first".

Hope this helps.

Kind regards,
Plamen Zdravkov
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Tags
TreeView
Asked by
Jon Ingersoll
Top achievements
Rank 1
Answers by
Plamen
Telerik team
Jon Ingersoll
Top achievements
Rank 1
Share this question
or