Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

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.

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, April 24, 2012

How Can I Print in Color in Visual Studio?


One issue that came up in class some time back was that a student was printing his code from Visual Studio when he noticed that all of his code was being printed in black and white. From a learning perspective, he sometimes likes to view his code on paper, mark it up by hand, draw arrows and in other ways interact with it and make it sense of it.

However, one of the helpful features of Visual Studio, of course, (and of most Integrated Development Environments) is the color coding. By default, comments are shown in green, strings of text in red, keywords in dark blue and so on. So the student wanted to see if there was any way to get Visual Studio to print the code using the color coding that shows up onscreen.

It turns out that in Visual Studio 2008 and 2010, the color coding isn't enabled for print-outs. However, there is an extension from Microsoft that can be loaded to enable it to print in color.

The upside is being able to print in color.

The downsides are:
1)      The extensions are not supported in the Express versions of the Visual Studio products, and so Microsoft's color printing extension cannot be loaded on those versions.
2)      Collapsible regions will be printed as expanded; they cannot be skipped from the printout.
3)      The new print dialog box doesn't enable printing line numbers, and so they can only be printed by enabling line number margins in Tools-->Options.
4)      Margins for the page itself cannot be altered in this version.

To review the documentation and/or install the Color Printing extension for Visual Studio, visit: http://visualstudiogallery.msdn.microsoft.com/00ec88c2-1553-47d2-8170-3c5baa0c6e44/?SRC=Home

Monday, July 25, 2011

Troubleshooting Ajax AsyncFileUpload Control

The ASP.Net Ajax Control Toolkit provides lots of interactive, feature-rich controls for the web developer. However, as my work transitioned from Visual Studio 2008 to Visual Studio 2010 products, I noticed a common problem with the Asynchronous File Upload control. The error message from trying to use the control was "The file attached is invalid".

 

If you're not familiar with this control, it behaves similarly to the normal File Upload control that's in the Standard section of the Tools panel in Visual Studio. Both versions of the control allow a user of the web application to browse for, select, and upload a file to the server. However, the Ajax toolkit's Asynchronous version allows the upload process to occur in real time (in the background) as the user continues to use the webpage, instead of forcing the user to wait for the page to be returned while the upload is being processed.

 

The issue appears to be with the control itself, but particularly when used in the .Net 4.0 framework, which is likely to be the default for Visual Studio 2010 products, unlike the 3.5 framework likely set as the default for Visual Studio 2008.

 

So, how do you fix the AsyncFileUpload that keeps telling you "The file attached is invalid"?

The Fix

Just add the ClientIDMode="AutoID" property to the control. This easy change allows the control to be properly identified. If you would like to control this at the web.config level, you could also consider using the following approach instead:



<pagecontrolRenderingCompatibilityVersion="4.0" clientIDMode="AutoID"/>


Of course, in that case you will want to be sure to test the rest of your controls to make sure this doesn't cause any problems elsewhere.

For additional reading on the topic, see:


- Eric Reid, Design Expert; CTT+, ACI (Adobe Certified Instructor), ACE (Adobe Certified Expert), i-Net+, IC3
LinkIn with Eric


Bookmark and Share

Monday, February 14, 2011

What a Model Really Is!

Recently, I have been doing training in Visual Studio 2010 and within the courses there are two design patterns discussed: Model-View-Controller (MVC) (Patterns and Practices: Model View Controller), and Model-View-ViewModel (MVVM)(THE MODEL-VIEW-VIEWMODEL (MVVM) DESIGN PATTERN). In the past I have done presentations on MVC however I had difficulty in properly explaining what the “Model” portion of it pertained to.

Today it dawned on me what this “Model” is: it is the business model of an application. It represents the entities that the developer has to work within the application. I originally thought that the Model represented the data model since I had been teaching Entity Frameworks. However the data portion is outside of the model. What this means is that the mechanism of retrieving the entities for the Model, and persisting changes in the Model into storage, are not part of the Model itself.

The Model is represented by the entities we are working with which is not a simple concept. Since if you are thinking in terms of data only it would be incorrect. I believe that is the first step in truly understanding the MVC and MVVM patterns, as well as Model-View-Presenter (MVP). It is important since when analysis is performed the context is the overall business/organization issues and entities, not just a database.

If you are interested, we have classes that cover some of these design patterns, specifically, MS10262 on Window Applications (WPF), MS10264 on Developing Web Applications, and MS10265 Data Access Solutions (Entity Frameworks). All of these courses are taught with Visual Studio 2010 (a wonderful upgrade) and both Visual Basic 10.0 (VB2010), and Visual C# 4.0 (VC2010) are used in the classes.

- Leslie Koorhan, .NET Expert;
MCT, MCSD (.NET), MCTS, MCDBA, MCPD LinkIn with Leslie

Bookmark and Share

Monday, February 7, 2011

Recommendation: CODE Magazine

I recently got a renewal to CODE Magazine.  This great magazine has really good articles for developers, and the source code in the magazine is color-coded, just like it is in the Visual Studio editors.  They also have sample code available on their website that you can copy for projects as well.

In the most recent issue, Jan/Feb 2011, they have an interesting article by the publisher of the magazine, Markus Egger. The story covers the Windows Presentation Foundation (WPF) and Silverlight ListBox. In the article, Markus shows that by using styles and templates you can turn that ListBox into almost any representation of multiple items that you can imagine. It is really fascinating and something I think that every WPF/Silverlight developer should know. In fact, if you are still doing Windows Forms, and really needed convincing that it was time to switch to WPF, this should do it. 

Another recommended article for reference is Getting Started with Windows Phone 7 Development


- Leslie Koorhan, .NET Expert;
MCT, MCSD (.NET), MCTS, MCDBA, MCPD LinkIn with Leslie

Bookmark and Share

Friday, December 3, 2010

Visual Studio Tips [VIDEO]



Instructor Leslie Koorhan gives some litte known tips on using Visual Studio 2010. Check out our Corporate Class Schedule for the next available Visual Studio 2010 class date!  

- Leslie Koorhan, .NET Expert;
MCT, MCSD (.NET), MCTS, MCDBA, MCPD LinkIn with Leslie

Bookmark and Share

Wednesday, December 1, 2010

Free Resources on Visual Studio 2010


Well, Visual Studio 2010 has been out for several months now, and it looks to be a super product. One of the nice things that Microsoft is doing is offering a lot of content for free to help explain and teach the features of VS2010.

For example, you may have heard of ASP.NET MVC (Model-View-Controller), which is a Microsoft template (actually, now MVC2) for developing web applications using what is known as the MVC design pattern. But there are other design patterns for developing applications. Here is a link for using the MVVM (Model-View-ViewModel) pattern for WPF and Silverlight applications: Problems and Solutions with Model-View-ViewModel.

Another recent discussion had to do with questions on what Microsoft is doing with data.

Anyway, I hope these give you something to think about until the next time. Coming in a couple of weeks, a long overdue course on Programming with C#, using Visual Studio 2010.


- Leslie Koorhan, .NET Expert;
MCT, MCSD (.NET), MCTS, MCDBA, MCPD LinkIn with Leslie

Bookmark and Share

Tuesday, October 26, 2010

Class Spotlight: MS-10175A Microsoft SharePoint 2010, Application Development

This class should be considered for certification and will help to prepare students for the 70-573 Exam.  This class is for experienced SharePoint 2007 developers who want to see the new features of SharePoint 2010.  

It showcases the ease of developing SharePoint applications with the built-in tools of Visual Studio 2010.  It introduces some of the new features of SharePoint Designer 2010 in the SharePoint web application development.  The developer candidate should be well versed in Visual Studio and the C# application language as this class does not teach these skills, it simply shows the student how to apply these skills to SharePoint development.

For more info on the course and to see upcoming dates on our calendar, click here

Once a student successfully completes this course, they can then take the MS-10232 course, which gets them into developing SharePoint Applications.

- Steve Nichols, SharePoint Expert; MCT, MCTS, MCSE LinkIn with Steve

Bookmark and Share

Wednesday, July 21, 2010

Visual Studio 2010: Now Released

Visual Studio 2010 is now out! It’s a very exciting product, with a host of improvements over the 2008 version and a bunch of new features. For example, the standard web template (for either a Web Application or a Web Site) now includes a stylesheet file (CSS), a master page, login page, registration page and about page. That means that before you even add one thing to the project, it is a working web app.

There are a lot of other new features, but one thing that stands out for me, is that much of the Visual Studio interface has been designed using Windows Presentation Foundation (WPF). For me, it’s exciting because it shows just what you can do using WPF. It also means that we have a lot of extra capability built into VS. For example, you can use zoom features on the designers and editors in VS2010. As an instructor, that’s awesome since many times while teaching I want to make sure students can see what I am doing. This allows me to bring it in closely.

With tons more things to like about Visual Studio 2010, I'll be covering a lot of things about the product in future posts. And don’t forget: Centriq’s first VS2010 offering comes in August when I will be teaching Introduction to Web Development with Microsoft Visual Studio 2010!


- Leslie Koorhan, .NET Expert;
MCT, MCSD (.NET), MCTS, MCDBA, MCPD LinkIn with Leslie

Bookmark and Share