Web Controls in DotNetNuke

Exclusive offer: get 50% off this eBook here
DotNetNuke 5.4 Cookbook

DotNetNuke 5.4 Cookbook — Save 50%

Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS

$26.99    $13.50
by John K Murphy | October 2010 | Cookbooks Open Source

In this article by John K. Murphy, author of DotNetNuke 5.4 Cookbook, we will cover the following topics:

  • Adding web controls to your Toolbox
  • Showing an e-mail link in a Datagrid
  • Showing checkboxes in a Datagrid
  • Showing a thumbnail image in a Datagrid
  • Creating labels you can edit
  • Suggest text while typing

 

DotNetNuke 5.4 Cookbook

DotNetNuke 5.4 Cookbook

Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS

  • Create and customize your own DotNetNuke website with blog, forums, newsletters, wikis and many more popular website features
  • Learn custom module development and rich content management with sample code and tips
  • Provides samples of styling and skinning a DotNetNuke portal
  • Offers advanced programming tips combining DNN with AJAX and JQuery
  • Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

Read more about this book

(For more resources on DotNetNuke, see here.)

Introduction

One of the powerful features of DNN is the variety of flexible and reusable controls that are available for custom module development. These include many of the web controls seen on the core DNN pages. In this article, we will see how to add these web controls to custom modules and tie them to the tables in the database.

In general, using these controls requires four simple steps:

  • Adding the control code to the View or Edit .ascx file
  • Adding a new property to the info object that will supply the values for the control
  • Binding the control to the values
  • Capturing the value from the control and saving to the database (if Edit page)

Adding web controls to your Toolbox

If you frequently use the visual editor in the development tool to layout your pages, this short recipe will show you how to add the DNN web controls to the Toolbox.

How to do it…

  1. Launch the Development Tool.
  2. Change the editor to Design mode.
  3. Make sure the toolbox is displayed.
  4. Right-click on the toolbox and select Choose Items….
  5. Click on the Browse button.
  6. Navigate to the /bin folder within the DNN source (DNNSource/website/bin).

    DotNetNuke 5.4 Cookbook

  7. Select the DotNetNuke.Webcontrols.dll and click on Open.
  8. Make sure the DNN controls are checked and click on OK.
  9. The web controls will now appear under the General section of the toolbox when you edit your code.

    DotNetNuke 5.4 Cookbook

  10. Next, we need to add a reference to DotNetNuke.WebUtility.dll. Right-click on the Employee project in the Solution Explorer and select Add Reference….
  11. In the pop-up dialog, click on the Browse tab and navigate to the folder holding the DNN source files (for example, My Documents\DNNSource\Website\bin).
  12. Select the file DotNetNuke.WebUtility.dll and click on OK.

Showing an e-mail link in a Datagrid

The Datagrid control is perfect for showing records from the database in a neatly formatted table. But the Datagrid can show many other types of information and in this recipe we will see how to display an e-mail hyperlink in a column.

Getting ready

In this recipe, we will extend the Datagrid.

In this recipe we are using a function to generate an e-mail address for our example. This keeps the recipe simple, but isn't really practical. In a real production environment you would store this in the database as part of the Employee table.

How to do it...

  1. Launch the Development Tool and load the Employee project.
  2. Double-click to open the ViewEmployee.ascx file.
  3. Locate the Datagrid in the code and add a new column just after the Salary column:

    <dnn:textcolumn datafield="Salary" headertext="Salary"/>

    <asp:TemplateColumn HeaderText="Email Contact">
    <itemtemplate>

    <asp:HyperLink id="hlEmail"
    NavigateUrl='<%# "mailto:" & DataBinder.Eval
    (Container.DataItem,"ContactEmail") %>'
    Text='<%# DataBinder.Eval
    (Container.DataItem,"ContactEmail") %>'
    Target="_new"
    runat="server" />
    </ItemTemplate>
    </asp:TemplateColumn>

    </Columns>
    </asp:datagrid>

  4. Next, open the EmployeeInfo.vb file.
  5. Find the Public Properties section and add the read-only property EmailAddress to provide an e-mail address constructed from the employee name:

    ' public properties

    Public ReadOnly Property EmailAddress() As String
    Get
    Return _EmpFirstName.Substring(0, 1) + _EmpLastName +
    "@yourcompany.com"
    End Get
    End Property

  6. Select Save All from the File menu.
  7. To check the results, build and deploy the module to a development portal for testing.
  8. Go to the ACME Employee page to see the list of employees. The new e-mail hyperlink will appear on the right-hand side.

    (Move the mouse over the image to enlarge.)

How it works...

In this recipe we saw the tasks to show an e-mail hyperlink in a Datagrid control:

  • We took the Datagrid control and added a new template column holding an e-mail hyperlink control
  • We added a new property to the EmployeeInfo object to provide an e-mail address for the Datagrid

Showing checkboxes in a Datagrid

An element that is useful to display in a Datagrid is a checkbox-like image to indicate the status of the database record. These are not functioning checkboxes but rather a visual indicator showing the data to be true or false.

The control works by having two images, one with a checkmark that is shown when the value is true. The other is an unchecked image that is shown when the value is false.

This recipe will work with any image indicating true or false. Checkbox-like images are used in other DNN modules so they are familiar to users, but you can experiment with your own images as well.

This recipe has two basic steps:

  • We will create a new property of the EmployeeInfo object called NewHire. This property checks the date of hire from the database and returns true if the employee was hired less than 30 days ago.
  • We will add a new column to the Datagrid that evaluates the NewHire property and shows one image if the NewHire is true and another image if the NewHire is false.

Getting ready

In this recipe we will extend the Datagrid.

How to do it...

  1. Launch the Development Tool and load the Employee project.
  2. Double-click to open the ViewEmployee.ascx file.
  3. The first step is to add a new column to the Datagrid that will show the checkbox images. We will use the Eval function to check the NewHire function. Locate the Datagrid and add a new column just after the Salary column:
          <dnn:textcolumn datafield="Salary" headertext="Salary"/>

    <asp:TemplateColumn HeaderText="New Hire">
    <itemtemplate>
    <asp:Image Runat="server" ID="imgApproved"
    ImageUrl="~/images/checked.gif" Visible='<%# DataBinder.Eval
    (Container.DataItem,"NewHire")="1" %>'/>
    <asp:Image Runat="server" ID="imgNotApproved"
    ImageUrl="~/images/unchecked.gif" Visible='<%# DataBinder.Eval
    (Container.DataItem,"NewHire")="0" %>'/>
    </ItemTemplate>
    </asp:TemplateColumn>

    </Columns>
    </asp:datagrid>
  4. Next, open the EmployeeInfo.vb file.
  5. Find the Public Properties section and add the read-only property NewHire that returns true or false if the employee was hired in the last 30 days:
     ' public properties

    Public ReadOnly Property NewHire() As Boolean
    Get
    Return (Today() - _HireDate).Days < 30
    End Get
    End Property
  6. Select Save All from the File menu.
  7. To check the results, build and deploy the module to a development portal for testing.
  8. Go to the ACME Employee page to see the list of employees. The new checkbox will appear on the right-hand side.

    DotNetNuke 5.4 Cookbook

  9. Although you cannot click on these checkboxes, they do provide a clear and easy to understand visual status for the records.

How it works...

In this recipe we saw the tasks to show checkbox images in a Datagrid control:

  • We took the Datagrid control and added a new template column holding two image controls, one checked and the other unchecked.
  • We added a new property to the EmployeeInfo object that returns true or false depending on the database record.
  • We bound the property to the control so that if the property was true then the checked image was displayed. If the property was false the unchecked image was displayed.

 

DotNetNuke 5.4 Cookbook Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS
Published: September 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Read more about this book

(For more resources on DotNetNuke, see here.)

Showing a thumbnail image in a Datagrid

Datagrids are a flexible control that can display a variety of information. In this recipe, we will see how to display a small thumbnail image in the Datagrid based on information in the Employee table.

Getting ready

In this recipe we will extend the Datagrid.

How to do it...

  1. First prepare some thumbnail images to display. Generally 64x64 is a good size but you can experiment and see what looks good. To keep it simple, name the images based on the employee name--first initial, and last name with .PNG extension.

    DotNetNuke 5.4 Cookbook

  2. Now we need to upload the images to the DNN site. Log in as Host user (syshost in our examples).
  3. Look under the Admin menu and select File Manager. Make sure Portal Root appears on the left side:

  4. Type SiteImages in the folder name textbox and click on Add Folder.
  5. Click on the Upload link.

    DotNetNuke 5.4 Cookbook

  6. Click on the Browse button and select a sample image.
  7. Click on Upload File to upload the image. Repeat for each image you have.

  8. With the images available to the site, we put the code in our module to display the images when we display employees.
  9. Launch the Development Tool and load the Employee project.
  10. Double-click to open the ViewEmployee.ascx file.
  11. Locate the Datagrid and add a new column just after the Edit and Delete links:
     <columns>
    <dnn:imagecommandcolumn CommandName="Edit"
    ImageUrl="~/images/edit.gif" EditMode="URL"
    KeyField="ItemID" />
    <dnn:imagecommandcolumn CommandName="Delete"
    ImageUrl="~/images/delete.gif" KeyField="ItemID" />


    <asp:TemplateColumn HeaderText="Icon">
    <itemtemplate>

    <asp:HyperLink id="imgView"
    ImageUrl='<%# DataBinder.Eval
    (Container.DataItem,"ImageURL") %>'
    NavigateUrl='<%# DataBinder.Eval
    (Container.DataItem,"ImageURL") %>'
    Text='<%# DataBinder.Eval
    (Container.DataItem,"ContactInfo") %>'
    Target="_new"
    runat="server"/>

    </ItemTemplate>
    </asp:TemplateColumn>

    <dnn:textcolumn datafield="EmpFirstName" headertext="First" />
  12. Next, open the EmployeeInfo.vb file.
  13. Find the Public Properties section and add the read-only property ImageURL that returns the URL of the images we uploaded (based on employee name):
    ' public properties

    Public ReadOnly Property ImageURL() As String
    Get
    Return "~\Portals\_default\SiteImages\" +
    _EmpFirstName.Substring(0, 1) + _EmpLastName + ".png"
    End Get
    End Property

    Public ReadOnly Property ContactInfo() As String
    Get
    Return _EmpFirstName + " " + _EmpLastName + " Hired: " +
    FormattedHireDate()
    End Get
    End Property
  14. Select Save All from the File menu.
  15. To check the results, build and deploy the module to a development portal for testing.
  16. Go to the ACME Employee page to see the list of employees. The employee images will appear on the left side.

    DotNetNuke 5.4 Cookbook

How it works...

In this recipe we saw the tasks to show images in a Datagrid control:

  • We created a set of images and uploaded them to the DNN site.
  • We took the Datagrid control and added a new template column holding an image hyperlink control.
  • We added a new property to the EmployeeInfo object that provided the image URL for the hyperlink.

Creating labels you can edit

In this recipe we will see how to create editable labels using the DNNLabelEdit control. You can see the DNNLabelEdit control at work in the Module titles of the DNN site that allows the administrator to edit the module titles directly on the page.

Getting ready

To follow along with this recipe you must have completed the following recipe:

  • Adding web controls to your Toolbox
  • Deploying a module as a standalone package

One of the important parts of this recipe is that once a label has been changed, we must save the new text somewhere. Fortunately DNN provides a place to save it: in the module settings. The module settings apply to all instances of a module regardless of how many pages they appear on (unlike Tab Module settings which are settings for a particular instance of a module). To access the module settings we use the routine UpdateModuleSetting, pass our module ID, a setting name, and setting value.

How to do it...

  1. Launch the Development Tool and load the Employee project.
  2. Double-click to open the EditEmployee.ascx file.
  3. Make sure the following register directive is at the top of the file:
    <%@ Register tagprefix="DNN" assembly="DotNetNuke.WebControls" 
    namespace="DotNetNuke.UI.WebControls" %>
  4. Find the HTML table holding the label and text controls and note the existing label control for the employee first name:

    <table width="650" cellspacing="0" cellpadding="0" border="0"
    summary="Edit Table">
    <tr valign="top">
    <td class="SubHead" width="125">
    <dnn:label id="lblEmpFirstName" runat="server"
    controlname="lblEmpFirstName" suffix=":">
    </dnn:label>
    </td>
    <td>
    <asp:TextBox ID="txtEmpFirstName" runat="server"></asp:TextBox>

  5. Delete the original label control and replace it with this new label code. The source code will now look like this:

    <table width="650" cellspacing="0" cellpadding="0" border="0"
    summary="Edit Table">
    <tr valign="top">
    <td class="SubHead" width="125">
    <DNN:DNNLabelEdit ID="dleEmpFirstName" runat="server" >[click
    here to edit]
    </DNN:DNNLabelEdit>
    </td>
    <td>
    <asp:TextBox ID="txtEmpFirstName" runat="server"></asp:TextBox>

  6. This is enough to let us edit the label, but we want to save the text changes as well. To do that we must handle the event when a label is retyped and save the information. Begin by opening the EditEmployee.ascx.vb file.
  7. Create a new event handler by pasting this code at the end of the Event Handlers region:

    Private Sub dleEmpFirstName_UpdateLabel(ByVal sender As Object,
    ByVal e As DotNetNuke.UI.WebControls.DNNLabelEditEventArgs)
    Handles dleEmpFirstName.UpdateLabel

    Dim modCtrl As New DotNetNuke.Entities.Modules.ModuleController
    Dim strLabel As String = e.text.tostring()

    ' save the updated label text in the module settings

    modCtrl.UpdateModuleSetting(ModuleId, "EmpFirstName", strLabel)

    End Sub

  8. Lastly, add the following code to the Page_Load procedure:

    If Page.IsPostBack = False Then

    ' load the label text from the module settings

    Dim strLabelText As String = CType(Settings("EmpFirstName"),
    String)

    ' if no text was saved in module settings, set it to [click here
    to edit]
    If strLabelText Is Nothing Then
    ' pull the default label text from the resource file
    strLabelText = Localization.GetString("lblEmpFirstName",
    LocalResourceFile)
    End If
    dleEmpFirstName.Text = strLabelText

  9. Select Save All from the File menu.
  10. To check the results, build and deploy the module to a development portal for testing.
  11. Go to the ACME Employee page and click on the edit icon (the little pencil) next to an employee to display the Edit Employee page.

    DotNetNuke 5.4 Cookbook

  12. Clicking on the label will unlock it and allow you to type a new label. When you leave the page the text is automatically saved. When you return, the label will show the new text.

How it works...

In this recipe we saw the tasks to create a DNNLabelEdit control:

  • We placed the control in the .ascx file
  • In the code behind the file we added an event handler to save the label text when it changes
  • We changed the Page_Load procedure to read the label text from the database

Suggest text while typing

The DNNTextSuggest control is a textbox that watches user input and suggests text as the user types. This behavior is frequently seen in search engines and other websites.

This control works by having a list of possible text phrases that it can search through as the user types. In this recipe, we will demonstrate this control by using the list of U.S. geographical states that is part of the DNN site along with a new field on the Edit Employee page.

Getting ready

To follow along with this recipe you must have completed the following recipes:

  • Adding web controls to your Toolbox
  • Deploying a module as a standalone package

How to do it...

  1. Launch the Development Tool and load the Employee project.
  2. In the Solution Explorer, look under the references and make sure your project includes a reference to DotNetNuke.WebUtility.dll.
  3. Double-click to open the EditEmployee.ascx file.
  4. Make sure the following register directive is at the top of the file:
    <%@ Register tagprefix="DNN" assembly="DotNetNuke.WebControls" 
    namespace="DotNetNuke.UI.WebControls" %>
  5. We're going to add a new row to the HTML table holding the Employee fields. Find the HTML table and insert the following code just before the </TABLE> tag.

    <tr valign="top">
    <td class="SubHead" width="200"><dnn:label id="lblSalary"
    runat="server" controlname="lblSalary" suffix=":">
    </dnn:label>
    </td>
    <td>
    <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="valSalary"
    resourcekey="valSalary.ErrorMessage"
    ControlToValidate="txtSalary"
    CssClass="NormalRed" Display="Dynamic"
    ErrorMessage="<br>Salary is required" Runat="server" />
    </td>
    </tr>

    <tr valign="top">
    <td class="SubHead" width="200">
    <dnn:label id="lblState" runat="server"
    controlname="lblState" suffix=":">
    </dnn:label>
    </td>
    <td>
    <DNN:DNNTextSuggest ID="txtState" runat="server"></DNN:DNNTextSuggest>
    </td>
    </tr>

    </table>

  6. Next, open the EditEmployee.ascx.vb file.
  7. Check the top the file and make sure it has the following imports:
  8. Imports DotNetNuke.UI.WebControls

    Imports DotNetNuke.Common.Lists

  9. Scroll down to the Private Methods region and add this procedure:

    #Region "Private Methods"

    Private Sub SuggestText(ByVal objNodes As DNNNodeCollection,
    ByVal strTypedText As String)

    Dim nodeStates As DNNNode
    Dim objList As New ListController()
    Dim lstStates As ListEntryInfoCollection =
    objList.GetListEntryInfoCollection("Region", "Country.US")
    Dim state As ListEntryInfo

    'loop through the collection and add it to the result set

    For Each state In lstStates
    If txtState.MaxSuggestRows = 0 Or objNodes.Count <
    (txtState.MaxSuggestRows + 1) Then
    ' add the state to the list of suggestions
    nodeStates = New DNNNode(state.Text)
    nodeStates.ID = state.Value
    objNodes.Add(nodeStates)
    End If
    Next

    End Sub

  10. Next, we must trap when text is typed into the control. Scroll down to the bottom of the Event Handlers region and add the following procedure:

    Private Sub txtState_UpdateLabel(ByVal sender As Object,
    ByVal e As DotNetNuke.UI.WebControls.DNNTextSuggestEventArgs)
    Handles txtState.PopulateOnDemand

    ' call the suggestion procedure and pass the text typed into the
    control
    SuggestText(e.Nodes, e.Text)

    End Sub

    #End Region

  11. Lastly, as we included a new label control, open the EditEmployee.ascx.resx file (under /App_LocalResources) and set the label text and Help prompt:

    lblState.Text: Home State

    lblState.Help: Type the name of the employee's home state.

     

    DotNetNuke 5.4 Cookbook

  12. Select Save All from the File menu.
  13. To check the results, build and deploy the module to a development portal for testing.
  14. Go to the ACME Employee page and click on the edit icon (the little pencil) next to an employee to display the Edit Employee page.

    DotNetNuke 5.4 Cookbook

  15. The new Home State field appears at the bottom. Unlike the other text fields, as you type the name of a Home State, the suggestion list will appear below the box. Click on the state name in the list and it will appear in the text box.

How it works...

In this recipe we saw the tasks to create a DNNTextSuggest control:

  • We placed the control in the .ascx file
  • In the code behind file we added a new procedure called SuggestText
  • The SuggestText procedure loaded the list of U.S. geographical states from the DNN core and created a list of suggestions
  • We added an event handler on the DNNTextSuggest control to display the list of suggestions when text is typed

See also

In this recipe we saw how the SuggestText web control works and how it is used to prompt for a text value. To keep the recipe simple it did not include the necessary code to load and save the value to the database.

Summary

In this article we covered the following recipes:

  • Adding web controls to your Toolbox
  • Showing an e-mail link in a Datagrid
  • Showing checkboxes in a Datagrid
  • Showing a thumbnail image in a Datagrid
  • Creating labels you can edit
  • Suggest text while typing

In the next article, Adding Web Controls to Custom Modules in DotNetNuke, we will take a look at some examples of web controls such as TreeView, TabStrip, and CAPTCHA validation.


Further resources on this subject:


DotNetNuke 5.4 Cookbook Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS
Published: September 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


John K Murphy

John K Murphy is a software industry veteran with more than 25 years experience as a programmer and database administrator. A graduate of the University of West Virginia he began writing computer games in the 1980's before pursuing a career as a  computer consultant. Over the years, John has enjoyed developing software in most major programming languages while striving to keep current with new technologies.

In his spare time, John enjoys scuba diving, skydiving and piloting small planes. He lives with his wife and two children in Pittsburgh, Pennsylvania.

Books From Packt


Silverlight 4 User Interface Cookbook
Silverlight 4 User Interface Cookbook

Microsoft Dynamics GP 2010 Cookbook
Microsoft Dynamics GP 2010 Cookbook

Microsoft Windows Workflow Foundation 4.0 Cookbook
Microsoft Windows Workflow Foundation 4.0 Cookbook

Building Websites with DotNetNuke 5
Building Websites with DotNetNuke 5

DotNetNuke Skinning Tutorial
DotNetNuke Skinning Tutorial

MySQL Admin Cookbook
MySQL Admin Cookbook

NHibernate 3.0 Cookbook
NHibernate 3.0 Cookbook

Oracle Database 11g – Underground Advice for Database Administrators
YUI 2.8: Learning the Library


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software