A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for the ‘ASP.NET Controls’ Category

TreeView.FindNode with PopulateOnDemand feature

Posted by kiranpatils on March 2, 2010

Challenge:

If you are using Tree View with PopulateOnDemand feature – for those who are new to PopulateOnDemand feature – It Indicates whether the node is populated dynamically for example if you have tree structure as below:

imageNow, Normally you can bind above tree view on page load directly with all child nodes. But if you have huge data then it will affect performance. So, to avoid performance issue we use PopulateOnDemand feature as name suggests Nodes will be populated on demand only[on click of + sign]. Now our new data binding code will load all root nodes only and set it’s PopulateOnDemand property to true as shown here:

Markup code

<asp:TreeView ID="LinksTreeView" Font-Names="Arial" ForeColor="Blue" OnTreeNodePopulate="PopulateNode"
           SelectedNodeStyle-Font-Bold="true" SelectedNodeStyle-ForeColor="Chocolate" runat="server">
       </asp:TreeView>

Code-Behind

protected void Page_Load(object sender, EventArgs e)
    {  
        if (!IsPostBack)
        {
            // bind first level tree
            TreeNode treeNode1 = GetTreeNode("1");
            treeNode1.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode1);

            TreeNode treeNode2 = GetTreeNode("2");
            treeNode2.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode2);

            TreeNode treeNode3 = GetTreeNode("3");
            treeNode2.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode3);

            // collapse all nodes and show root nodes only
            LinksTreeView.CollapseAll();
        }
    }

private static TreeNode GetTreeNode(string nodeTextValue)
    {
        TreeNode treeNode = new TreeNode(nodeTextValue, nodeTextValue);
        treeNode.SelectAction = TreeNodeSelectAction.SelectExpand;
        treeNode.PopulateOnDemand = true;
        return treeNode;

    }

protected void PopulateNode(Object sender, TreeNodeEventArgs e)
    {

        // Call the appropriate method to populate a node at a particular level.
        switch (e.Node.Text)
        {
            case "1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.3"));
                break;
            case "2":
                // Populate the second-level nodes.               
                e.Node.ChildNodes.Add(GetTreeNode("2.1"));
                e.Node.ChildNodes.Add(GetTreeNode("2.2"));
                e.Node.ChildNodes.Add(GetTreeNode("2.3"));
                break;
            case "3":
                // Populate the third-level nodes.               
                e.Node.ChildNodes.Add(GetTreeNode("3.1"));
                e.Node.ChildNodes.Add(GetTreeNode("3.2"));
                e.Node.ChildNodes.Add(GetTreeNode("3.3"));
                break;
            case "1.1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.3"));
                break;
            case "1.1.1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.3"));
                break;
            default:
                // Do nothing.
                break;
        }
    }

Great! Now we are ready just run your application and see the power of PopulateOnDemand feature. Whenever you expand any node[by clicking on plus sign] it will call PopulateNode Method because in tree view’s markup we have binded it.

Now, the main problem is here. Suppose you have a requirement in which you have to find 1.1.1.1 Node –which is at path 1/1.1/1.1.1/1.1.1.1. You will shout and say use TreeView’s FindNode method and provide path like this :

LinksTreeView.FindNode(“1/1.1/1.1.1/1.1.1.1”);

can you pls give a try and check does it works? it won’t because I’ve already tried :) let me tell you why – Because 1.1.1.1 node is not loaded yet and it’s parent node 1.1.1 is also not loaded yet and so on still 1.1. Just 1 has been loaded. So, let’s see how we can solve this challenge:

Solution:

After goggling a bit and braining a lot i found the following way:

Main aim is to load 1.1.1.1 but it’s the last node and to load it all it’s parent’s should be first loaded. Here’s the simple way of doing it:

LinksTreeView.FindNode(“1”).Expand(); // it will find node and call expand method so it will load 1.1 which is first child of 1

LinksTreeView.FindNode(“1/1.1”).Expand();  //loads 1.1.1

LinksTreeView.FindNode(“1/1.1/1.1.1”).Expand(); //loads 1.1.1.1

LinksTreeView.FindNode(“1/1.1/1.1.1/1.1.1.1”).Expand(); //Cheers we reached there!

Now, above code is bit hard-coded and i am against of hard-coding so wrote one generic method which works for any level of node finding[txtPath is one textbox which provides path to find]

protected void btnSelect_Click(object sender, EventArgs e)
   {  
       //It will not work because as it is populateondemand
       //this call will never find node because of populateondemand
       TreeNode foundNode = LinksTreeView.FindNode(txtPath.Text);
       if (foundNode == null)
       {
           // Now i am doing different way
           string selecteValuePath = txtPath.Text;
           string[] selectedValues = selecteValuePath.Split(LinksTreeView.PathSeparator);

           string findValueQuey = string.Empty;
           for (int counter = 0; counter < selectedValues.Length; counter++)
           {
               string fValuePath = string.Empty; ;
               if (counter == 0)
               {
                   // store 1
                   fValuePath = selectedValues[counter];
               }
               else if (counter < selectedValues.Length)
               {
                   // now path is 1/1.1
                   fValuePath = findValueQuey.ToString()
                       + LinksTreeView.PathSeparator
                       + selectedValues[counter];
               }

               //1/1.1/1.1.1/1.1.1.1
               foundNode = LinksTreeView.FindNode(fValuePath);

               if (foundNode != null)
               {
                   foundNode.Expand(); //loads child node
                   foundNode.Select();
                   // stored 1
                   // stored 1/1.1
                   findValueQuey = fValuePath;
               }               
           }
       }
       else
       {
           Response.Write("Node found : " + foundNode.Value);
       }
   }

Happy Node Finding!

Posted in ASP.NET, ASP.NET Controls | Tagged: | 1 Comment »

Showing Default Date and Visible Date with Calendar control

Posted by kiranpatils on September 2, 2009

Challenge:

if you are using Calendar control to show Birthday of your friend. So, when you run the application it will show whose b’day is coming in this month or next month or next month …. So, you can be ready for a treat :) . The Challenge here is how to select that particular date and how to make it visible while user runs the application?

Solution:

You can set SelectedDate of Calendar Control to show date selected like this:

DateTime dtBirthday = getUpcomingBirthday(); //assume this method returns upcoming b’day in DateTime

calBirthday.SelectedDate = dtBirthday.Date; //use Date here else it won’t work

You can set VisibleDate of Calendar Control to show that date:

calBirthday.VisibleDate= dtBirthday.Date; //use Date here else it won’t work

Here DateTime.Date part it too important. Else it won’t work. Do you know why? i know but it’s homework for you guys :)

Cheers

Posted in ASP.NET, ASP.NET Controls | Leave a Comment »

Form Reset With Validation Control

Posted by kiranpatils on September 2, 2009

Challenge:

Reset button won’t clear validation control messages.

Solution:

For that you have to write JS onclick of reset button and do hide it like this:

document.getElementById(“regurlarexpressionID”).style.visibility = “hidden”;

See this link:

http://forums.asp.net/t/567612.aspx

Posted in ASP.NET, ASP.NET Controls | Leave a Comment »

New Password should not be same as old password with ChangePassword Control

Posted by kiranpatils on June 9, 2009

Challenge:

You have dropped ChangePassword Control which allows user to change password. User will provide Current Password, New Password. But you want that New Password can’t be same as Old password..for security reason…how can you do this?

Solution:

1. Hook onchangingpassword-[Occurs before the password for a user account is changed by the membership provider]. event of ChangePassword Control:

<asp:ChangePassword ID="ChangePassword1" runat="server"
onchangingpassword="ChangePassword1_ChangingPassword">
</asp:ChangePassword>

2. In Handler compare password:

protected void ChangePassword1_ChangingPassword(object sender, LoginCancelEventArgs e)
{
if (<span style="color:#000000;">ChangePassword1.CurrentPassword == ChangePassword1.NewPassword)</span>
{
//TODO Show Message
//Cancel the event

e.Cancel = true;//set it to true else it will show the msg as well as change the password also
}
}

Happy Programming!!:)

Posted in ASP.NET, ASP.NET Controls | 7 Comments »

<tbody>using Table control

Posted by kiranpatils on May 30, 2009

Challenge:

How I generate <tbody> tag using Table, TableRow, etc … controls ?

I want to generate table o/p like this:

<table border="1">
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

Src : http://www.w3schools.com/TAGS/tag_tbody.asp

I want to create table like this from my code

behind using .net f/w classes.

Solution:

TableRow.TableSection is the solution for it:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.tablerow.tablesection.aspx

for whatever row you create just provide it’s TableSetion property to appropriate section e.g Body,head etc.

Hope this helps

Happy Programming!!

Posted in ASP.NET, ASP.NET Controls | Leave a Comment »

But how do I run JavaScript onLoad? with MasterPages

Posted by kiranpatils on March 11, 2008

Today, I came across good situation after a page load i want to check that some Hidden variable contains what?. But how can i add javascript which runs Onload..some sharp people says that add it in javascript’s onLoad method. But hey sharp i am using Masterpages. So i can’t add it in Master page’s Body tag. Because so many of my pages referes that master page and don’t want that functionality for all pages i want on one specific page. Really good problem…don’t worry i have its solution also.

Problem

i want to call “LoadData” function of javascript OnLoad event of page with Master Page. I have my.js file which holds this function

Solution

ClientScript.RegisterStartupScript(this.GetType(), “LoadData“, “LoadData();”, true);

     Explanation:

ClientScript = Page.ClientScript Property Gets a ClientScriptManager object used to manage, register, and add script to the page. [http://msdn2.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx]

RegisterStartupScript : Registers the startup script with the Page object using a type, a key, a script literal, and a Boolean value indicating whether to add script tags.

ClientScriptManager..::.RegisterStartupScript Method (Type, String, String, Boolean) [http://msdn2.microsoft.com/en-us/library/z9h4dk8y.aspx]

This script will run after Page-Load event so [MSDN says if run before page_load] . But working for me

LoadData = Key to register function

LoadData();=function to call

true = Add script tag or not [NOTE: Must do this to true] .

Now put anything in LoadData() function under .js file that’s it.

Another Problem and its solution:

I want to take confirmation from User Yes/no and based on input i need to proceed but i forgot it how to do..the method is use confirm(“MESSAGE”) in javascript returns True/false. for example:

var answer = confirm(“YES/NO?”);
if(answer)
alert(“YES”);
else
alert(“NO”);

Enjoy!!

Posted in ASP.NET, ASP.NET Controls | 1 Comment »

Formatting Date and Time in GridView

Posted by kiranpatils on March 10, 2008

Today, I am playing with Gridview and have to show data in it from SQL SERVER 2005. it has a field called as “JoiningDate” bounded with column “JoiningDate”. it was working fine it was showing date in the format like this: 2007-11-27 10:00:00.000 but i want to show it like this “11 Dec 2007″. I found it from MSDN. so here it is!!

Old Code[O/P=2007-11-27 10:00:00.000]:

<asp:BoundField DataField=”JoiningDate” HeaderText=”JoiningDate” / >

New one [O/P = 11 Dec 2007]

<asp:BoundField DataField=”JoiningDate” HeaderText=”JoiningDate” DataFormatString=”{0:dd MMM yyyy}” HtmlEncode=”False”/ >

Explanation

Two main tags helped me too achieve this:

1. DataFormatString: you can specify format to display string.

dd = Date

MMM = Month

yyyy = year

2. HtmlEncode: the field are HTML Encoded before they shown to bound field.Default true

NOTE: if you don’t do HTMLEncode=”False” .it won’t work. Because default it true.

References:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstandarddatetimeformatstrings.asp

http://msdn2.microsoft.com/en-us/library/system.datetime.tostring(VS.71).aspx

Hope it will help you too as it helped me..

Posted in ASP.NET, ASP.NET Controls | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 102 other followers