Tuesday, October 30, 2012

How do I use FindControl() in ASP.NET? When should I use FindControl()?

When coding ASP.NET pages, it often becomes necessary to call on a control from the code-behind page that is not directly available. Your first hint that you are in this situation is when you know the name of the control you are trying to access, but it does not show up in Visual Studio's Intellisense dropdown. Assuming you are actually calling the control by its correct ID (double-check!) then the reason it does not show up in Intellisense (and why you cannot call on it directly from the ASP.NET code-behind file) is usually because the control is housed inside some other structure.
There are several situations that can cause this, including but not limited to these three:
  1. Calling on a control, such as a textbox, that you defined on the page that used a CrossPage Postback to load this page.
  2. Calling on a control, such as a label, that you defined in the MasterPage associated with this content page.
  3. Calling on a control, such as a checkbox, that you defined in a templated control of a DetailsView on this page.
In all of these situations, the control you want to access is actually being built or housed by another control. To access it, you need to start by calling on the item you can access directly from the code-behind, then drill down into it using the FindControl() method.

The FindControl() method requires a string argument to be passed with the exact ID of the control being sought. A new Control object is returned in memory, with all the same properties and values of the one that was found. So you can use it to get the control's information or manipulate the control as needed.

Common Trip-ups

In case you don't call on the string ID properly (no Intellisense help for that!) or if under the current runtime circumstances, there is no value whatsoever for the Control you seek, you will run into a NullReferenceException. The Message property for this exception is "Object reference not set to an instance of an object". You can avoid this by first testing to make sure the control you are looking to call FindControl() from exists before trying to use it to call the method.

Keep in mind that because the FindControl() method returns a Control object, you will usually need to unbox that object to the more specific type of control you were actually looking for. So in case 1, cast it back to a TextBox. In case 2, cast it back to a DropDownList. In case 3, cast it to a CheckBox.

Also, realize that it is possible that the structure you need to dig through may be more complicated than it at first appears. Here is some sample code using FindControl() for cases 1-3, followed by a 4th example and the code it would require.

Case 1: TextBox1 available from PreviousPage property because it was passed using CrossPage Postback

protected void Page_Load(object sender, EventArgs e)
    {
        /*In a cross-page postback, be sure to test if
         * the page loaded with PreviousPage info before trying
         * to use it. If it's null, inform user of problem.
         * */
        if (PreviousPage != null)
        {
            TextBox tbName =
                (TextBox) PreviousPage.FindControl("TextBox1");
            lblName.Text = tbName.Text;
        }
        else
        {
            //Notify the user to start on the right page
            lblName.Text = "Please retry from the correct page.";
        }
    }


Case 2: DropDownList1 available from Master property because it was generated there for the Content Page

protected void Page_Load(object sender, EventArgs e)
    {
        /*Access the Label1 defined on master page from this
        * content page and assign its Text property. Each
        * content page will have unique content for this
        * label on the masterpage.
        * */
        Label lblPage = (Label)Master.FindControl("Label1");
        if (lblPage != null)
        {
            lblPage.Text = "Northwind Products Catalog";
        }
    }


Case 3: Checkbox1 available from DetailsView1 that generates it

protected void CheckBox1_PreRender(object sender, EventArgs e)
    {
        //waits until PreRender event to check the checkbox
        CheckBox cbIsActive =
            (CheckBox)DetailsView1.FindControl("CheckBox1");
        cbIsActive.Checked = true;
    }


Case 4: TextBox1 available from PreviousPage property due to CrossPagePostback. But because a MasterPage is also involved (the posted back page is a Content Page) the FindControl() path is more elaborate.

protected void Page_Load(object sender, EventArgs e)
    {
        /*Since we are involved with a masterpage, but we want
        * info on a control in PreviousPage (because of
        * crosspage postback or Server.Transfer), go through:
        * > PreviousPage> Form> ContentPlaceholder> desired control
        * */
       if(PreviousPage != null)
       {
            TextBox tbName = (TextBox)PreviousPage.Form.
            FindControl("ContentPlaceholder1").
            FindControl("TextBox1");
        }
        else
        {
            //Notify the user to start on the right page
            lblName.Text = "Please retry from the correct page.";
        }
    }   


The 4th example introduces a wrinkle because of the additional complexity of a crosspage postback combined with a masterpage. For an excellent write-up of how this actually gets built behind the scenes (and why you need to go through the PreviousPage's Form, then find its ContentPlaceHolder before you can find the TextBox inside it, see K. Scott Allen's OdeToCode.com Master Page article which includes the image below.)
Ode to Code Master Page hierarchy diagram

These types of wrinkles come up now and again when using FindControl() with more elaborate structures or controls housed inside of other controls, some of which may not be immediately apparent to you. Picking them apart is all part of furthering your capabilities with this method.

INamingContainer Sidebar

As a last technical sidenote, structures that wind up defining their own ID namespace on the page for controls housed inside them tend to implement the INamingContainer interface - meaning they must implement functionality to do just that. This is done to ensure that default ID's, like "Label1", aren't used repeatedly because some structure is automatically generating them. So just because a DetailsView builds label controls within its structure, we don't want it to generate an ID that might already being generated or used elsewhere on the page. So the DetailsView uses a naming convention for each label it generates to associate it with the control that created it – here, the DetailsView.

A standard ASP:Label control with a default ID of "Label1" would be adaptively rendered into HTML as:
<span id="Label1">Dynamically-Assigned Text Here</span>

Whereas a label control generated by a DetailsView with a default ID of "DetailsView1" would be adaptively rendered into HTML as:
<span id="DetailsView1_Label1">Dynamically-Assigned Text Here</span>

For more information, see also the MSDN information regarding the INamingContainerinterface.

At the end of the day, the FindControl() is a staple in your ASP.NET toolbox, and finding useful opportunities to employ it will improve your web development skillset.

Wednesday, September 5, 2012

Improvements to the Windows Server 2012 OS

With Windows Server 2012 becoming available in the coming days, it's important to take a look at the changes to the OS to support networking. The primary purpose of the OS is to support private cloud implementations, as well as to take Microsoft's virtualization technologies to another level. To accomplish these goals, Microsoft has had to address a couple of issues that have limited the Windows Server OS in the past.

First of all, Microsoft has introduced NIC Teaming as a software solution. Historically, NIC teaming has been a feature brought to the data center by the hardware vendor, and I expect that to continue. Personally, my experience has been to stick with certain hardware-based solutions rather than jump in up to my neck with software-based solutions. That said, there have been times that Microsoft has provided an adequate vendor-agnostic solution. Time will tell if they've achieved that goal with their NIC Teaming solution. One of the better articles on this feature can be found here: http://blogs.technet.com/b/privatecloud/archive/2012/06/19/nic-teaming-in-windows-server-2012-brings-simple-affordable-traffic-reliability-and-load-balancing-to-your-cloud-workloads.aspx. Essentially, it comes down to fault-tolerance and load-balancing, and the advantages of being able to mix and match hardware from different vendors.

The other aspect of Windows Server 2012 networking features that you should look at is the VLAN support in Hyper-V. It's no secret that Microsoft is tackling a number of challenges in the virtual network and virtual machine space to challenge the industry leader in network virtualization and "Infrastructure as a Service" with this release. To do that, Microsoft has had to beef-up their virtualized network offerings. Once again, time will tell if they have succeeded or not, but for those intrepid souls willing to take the leap, at least in a lab environment, I'd point you at this article by one of the more respected folks in on the MS side of the table, Deb Shinder. Her in-depth analysis can be found here: http://www.windowsnetworking.com/articles_tutorials/Windows-Server-2012-Network-Virtualization-IaaS-On-Premises-Hosted-Private-Cloud-Infrastructure-Part2.html

These two features are merely a starting point for one's exploration of the networking features, but these two should be enough to pique the interest of the Data Center admins. Have fun in the lab!

Thursday, August 9, 2012

Visual Studio Tips and Tricks, Part III: Outlining with Collapsible Sections and #region

Eric Reid
This is part 3 of a 3-part series on Visual Studio Tips and Tricks. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.

Collapsible Sections

If you aren't taking advantage of various outlining features available in Visual Studio, you are missing out.  In C# and HTML/ASP code, some blocks of code are automatically marked as collapsible by a + symbol in the far left margin of the code block's opening line. (It's just to the right of the line number if you have those enabled).

The C# code block with a plus sign at line 66, indicating a collapsible region for the method block.

If you click on the + symbol, it will collapse the code block to display a much-abbreviated version of the block on one line. The abbreviated code block will be shown with ellipses (…) to denote the change in display. And if you're using line numbers, you'll see there is a jump from the starting line down to the next line number where the code block leaves off. Also, the + symbol changes to a - symbol. Clicking the - symbol will expand the code block back to its original size.

The C# code after collapsing the section. Note the line jump from 66 to 79, and the … abbreviation.

The benefit is being able to see the bigger picture with your code after that block is collapsed within the greater structure.


Note that collapsing code blocks in this way does absolutely nothing to affect the functionality of the code – it will still run as written. Instead, its job is to help you view the code you want at a glance. This can also help to see where a large code block ends or to help verify your opening and closing syntax.


#region Directive

In addition to the built-in collapsible sections you'll find in your code in Visual Studio, you can also manually add your own in C# (and even give them a "comment-style name") using the #region directive.


The C# code before adding a collapsible #region directive.

To add your own collapsible sections in C#:
  1. Place your cursor in the line above the section of code you want to make collapsible.
  2. Type #region
    • Optionally, type additional text to act as a comment-style name on the same line. (This additional text will not be compiled, but will be displayed when you collapse the region).
  3. Place your cursor at the end of the section you are making collapsible.
  4. Type #endregion

The C# code after adding a collapsible #region directive. This one also includes an optional comment-style name of "Variables Declaration" on the same line as the opening #region.

You can now collapse the #region directive area like any other collapsible section:
  • Click the + symbol in the left margin to collapse the region.
  • OR click the - symbol in the left margin to expand it again to its full size.

The C# code after collapsing the #region directive. (Note that because we added a comment-style name after the region, that is what is displayed after the collapse.)

Tuesday, August 7, 2012

Visual Studio Tips and Tricks, Part II: Format Spacing

Eric ReidThis is part 2 of a 3-part series on Visual Studio Tips and Tricks. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.

Visual Studio products will typically help with formatting the spacing of your code (including C#, HTML, CSS, etc.) by adding its form of standard spacing as you add line breaks or spaces within certain common structures – nesting indents for nested code blocks or tags, or adding spaces after some characters. However, it's easy (with copy-and-paste or tinkering) to get these out of whack.

To apply Visual Studio's standard spacing to your code you can use the Format Document or Format Selection features to update either the entire document or just your selected code.

The HTML code above is clearly using non-standard spacing.

Format Selection

To quickly format the spacing for the selected code:
  1. Select the code to format.
  2. Format the selection's spacing by either using the menus or shortcut keys:
    • Menu system →Edit menu, Advanced submenu, Format Selection
    • OR Shortcut keys →CTRL+K, then release and CTRL+F
Using Visual Studio's Format Selection feature.

The HTML code after the Format Selection feature has been applied. (Note that only the selected code, and those lines immediately before and after, have been updated.)

Format Document

To quickly format the spacing for the whole document, by using either the menus or shortcut keys:
  • Menu system →Edit menu, Advanced submenu, Format Document
  • OR Shortcut keys →CTRL+K, then release and CTRL+D

The HTML code after the Format Document feature has been applied. (Note all lines have been updated.)

Saturday, August 4, 2012

Visual Studio Tips and Tricks, Part I: Surround With

Visual Studio software products are a common and fundamental tool for most ASP.NET developers (and can also be used by developers and web designers for many environments). The following 3-part series illustrates a few quick tips and tricks that may help you with your work using these applications. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.




In this series, we'll look at the following quick-use features to speed up your code work:
  • Surround With
  • Format Document/Selection
  • Collapsible sections (and the #region)

Surround With

A common coding conundrum is the need to "wrap" some tag or code block around another section of code. The manual approach to this would be to type the opening tag or code block before the section to be surrounded; then scroll down to the end of that section and type the closing tag or code block afterwards.

A shortcut for these steps is to use the Surround With feature of Visual Studio:
  1. Select the code to surround with some other common tag or code block (such as an HTML div or a C# if block).
  2. Right-click on the selection and choose "Surround With…"
    • Alternative methods:
      • Menu system → Edit menu, IntelliSense submenu, Surround With…
      • Shortcut keys → CTRL+K, then release and CTRL+S
  3. Below the selected code, a pop-up menu will either display folders for different types of snippets (double-click the folder to enter), or it will display allowable snippets for that context.
  4. Double-click the desired tag or code block to surround the selected area.

Code before Surround With
In this example, the C# code should only be run if the number2 variable does not equal zero. It's a prime candidate to Surround With a C# if statement.


Applying Surround With to code, step 1
The C# code after it's been selected and right-clicked for the Surround With feature.


Applying Surround With to code, step 2
After selecting Surround With, the pop-up menu offers various snippets for surrounding the code.


Code after applying Surround With for an IF statement
The C# code after using Surround With to wrap the if statement around the code, and updating the statement's condition to only run when the number2 variable doesn't equal 0.

In the case of adding a standard if block for C#, be sure to choose the 2nd if listed (not the first one preceded by the # sign).

Tuesday, July 10, 2012

HTML5 and the Future of the Universe

Web site people are always catching up. You get involved in an extended project and by the time you're done, they've changed the rules again and it's time to learn a new technology. I used to think this was a problem. Now I see it as a responsibility to manage the information of an ever expanding set of hardware devices that are becoming digital.

As these digital devices become of age, they mature into a web access point because of the value it adds to the device. Some devices like tablets are born with the ability to talk to the web at birth. Others, like DVD players, had to wait until they grew up.

HTML5 and CSS3 are expanding to fill the needs of the digital appetites of these new devices. As we innovate to market test a device at every screen size possible from phone to tablet to TV, the older development technologies will continually be updated until they break. So far, HTML and CSS are holding their own. CSS not so much. Even the old dog, JavaScript, is doing well but has some sturdy jQuery and CoffeeScript crutches.

The raft of programming languages not originally focused on the web that try to manage that environment push the simple text retrieval process to be more app like. In their desire to improve the unique asynchronous request-response communication model, they, in my mind, will eventually destroy it. Face it, it's slow. You can do faster communication with AJAX which is why you see Google using so much of it on their web apps. It's why jQuery Mobile designed their GUI library for speed with AJAX so much that it's the primary communication model that tolerates the web request model.

Now a newer model of finer grained I/O control in JavaScript is starting to appear called the WebSocket API. Did you not see this coming? It's not the end until each language has a way to use a simple library of functions/methods to talk to any device of your choice.

Languages are shifting little in popularity. A recent TIOBE trend announcement showing that the iOS platform language of choice, Objective-C, has been the faster gainer over the last two years to take the #3 spot on the chart, is the only major change. With Java trending downward and losing the lead to C, a venerable stalwart, I'm not seeing where anybody is picking up the slack. C# is on a slow trend upwards but not that much. Even php is losing ground.

My guess is that JavaScript is picking up the slack from reading language popularity articles. You can run a survey of projects on StackExchange and Github and find out that JavaScript has the top ranking there. Hacker News put JavaScript in the top three as well with Python and Ruby taking the top spots. Even job rankings on Dice.com show JavaScript in the top three to get a better sense of real world usage. Book sales from O'Reilly put JavaScript at #2 showing a mix of business and hobby use.

The next step for JavaScript would be to revive the server side version of the language and make it as available as php is for Apache. Then the major languages would write APIs to talk to JavaScript and we would have a programming interface for the web. Oh, yeah, and somebody do something in JavaScript to make CSS easier to work with. LESS is a good start.

So, if you are a web person, the future of the web looks like it centers on web application development and JavaScript is taking center stage. APIs will be promulgating and JavaScript/jQuery/minor language support plug-ins will be promoted. One of the APIs that is next on my bucket list is YQL. I think with the first book out on YQL in a few months from O'Reilly, we'll see an interest in mining the data of the web from JavaScript languages.

Excuse me now, I have to get back to the future and read about what's coming so when I start working again I won't be too far behind.



By: Doug Hoff

Monday, July 9, 2012

Do the Splits! See 2 Different Parts of the Window!




Do the splits!

Sometimes it is useful to be able to view the beginning of a document as well as the middle or end so that you can compare the content, formatting, etc. This is easily accomplished by splitting the Window. 




1.    From the View tab, in the Window group, choose Split.



2. Your mouse pointer will now have the split (which appears as gray bar with a double arrow), attached to it. Simply click where you want to split the Window into two, generally somewhere near the middle. You can move the split later if you wish!
 
The Window will now be divided into two separate panes, each having individual scroll bars and zoom settings!


 
You can move the split by clicking and dragging it with your mouse, or double click the split to remove it.

OK - Now that you are convinced this is a useful view, here is the shortcut!