Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for ASP.NET

February 1, 2010

ASP.NET: Mega Menus

Filed under: ASP.NET,C#,VB.NET @ 5:10 pm

I have been giving much thought to ASP.NET and Silverlight menus of late. While doing research on existing sites and how they are handling menus, I came across the concept of a "mega menu".

A mega menu is basically a drop down menu that contains many, many options. It provides a user with a quick way to navigate to a particular location on a site. Here is one example:

image

Hovering over the Technology tab displays a large set of menu options [highlight in blue is mine].

This looks like a very interesting and user-friendly way to provide the user with a large number of choices. And it is DEFINITELY better than lots of fly-out menus. Seems like a good design for eCommerce types of sites where you want your potential customer to quickly find your products.

Check out a set of good mega menu examples here.

This is not to say that every menu should be a mega menu. In fact, I find that most line of business applications (non-eCommerce) require a different approach. Primarily because line of business application often need to perform a set of related tasks and not just find products.

Enjoy!

January 31, 2010

ASP.NET: ListBox Tooltip

Filed under: ASP.NET,C#,VB.NET @ 6:47 pm

The ASP.NET ListBox does not display a horizontal scroll bar by default, which can be a problem if any of your list items are too long to fit. One solution to this problem is to use a tooltip. As the user moves the mouse over the ListBox entries, the full text appears in a tooltip.

image

The code to accomplish this is as follows:

In C#:

private void LB_PreRender(object sender, System.EventArgs e)
{
    foreach (ListItem item in LB.Items) {
        item.Attributes.Add("title", item.Text);
}

In C#, you also need to set up the event handler. In this example, the event handler is set up in the Page_Load event, but you could put it where it makes sense for your application.

LB.PreRender += LB_PreRender;

In VB:

Private Sub LB_PreRender(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles LB.PreRender
    For Each item As ListItem In LB.Items
        item.Attributes.Add("title", item.Text)
    Next
End Sub

The ListBox, named LB in this example, has a PreRender event. In the PreRender event the code loops through the ListBox items and sets the title attribute to the text of the item.

Use this technique any time you want to display a tooltip over your ListBox items.

Enjoy!

January 26, 2010

ASP.NET: ListBox Scrollbar

Filed under: ASP.NET,C#,VB.NET @ 9:46 pm

This one is in the category of obvious once you know how to do it. But having done Silverlight of late, I could not recall how to turn on the scrollbar in a ASP.NET ListBox. There is no scrollbar property of any kind.

A bit of "guess and check" with Bing provided lots of custom control solutions, which were more than I wanted to do for one little list box.

So I finally just tried Intellisense to see what properties and methods were available. And there was a Rows property and it worked!

To turn on the scrollbar in a ListBox, just set the Rows property to the number of items to display. If  there are more than the defined number of items in the list, the scrollbar will automatically appear.

In HTML:

<asp:ListBox id="LB" runat="server"
    Rows="6">
    <asp:ListItem>Test1</asp:ListItem>
    <asp:ListItem>Test2</asp:ListItem>
    <asp:ListItem>Test3</asp:ListItem>
    <asp:ListItem>Test4</asp:ListItem>
    <asp:ListItem>Test5</asp:ListItem>
    <asp:ListItem>Test6</asp:ListItem>
    <asp:ListItem>Test7</asp:ListItem>
    <asp:ListItem>Test8</asp:ListItem>
</asp:ListBox>

The result appears like this:

image

The Listbox displays the first 6 items as per the Rows property. Since there are 8 items, it automatically displays the scrollbar.

Enjoy!

January 25, 2010

ASP.NET: Selecting a Row in a GridView

Filed under: ASP.NET,C#,VB.NET @ 3:25 pm

Once I had my ASP.NET GridView in place (see this prior post), the next thing I wanted to do was select a row and go to a review/edit page. But I didn’t want to add the "Select" or "Edit" buttons. It seemed more natural for the users to simply click on the row.

I used Bing and followed my always helpful "guess and check" method. I found quite a few links to solutions for clicking on a row in the GridView control. Some didn’t work at all. Some worked if you turned off enableEventValidation. Some worked only if you did not try to page the results.

Here is a simple solution that works with any GridView and supports paging. It goes into the code behind file for the page containing the GridView. In this example, the GridView is called "CustomerGridView".

In C#:

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
    foreach (GridViewRow row in CustomerGridView.Rows) {
        if (row.RowType == DataControlRowType.DataRow) {
            row.Attributes["onmouseover"] = 
               "this.style.cursor=’hand’;this.style.textDecoration=’underline’;";
            row.Attributes["onmouseout"] = 
               "this.style.textDecoration=’none’;";
            // Set the last parameter to True
            // to register for event validation.
            row.Attributes["onclick"] = 
             ClientScript.GetPostBackClientHyperlink(CustomerGridView, 
                "Select$" + row.DataItemIndex, true);
        }
    }
    base.Render(writer);
}

In VB:

Protected Overrides Sub Render(ByVal writer As _
                               System.Web.UI.HtmlTextWriter)
    For Each row As GridViewRow In CustomerGridView.Rows
        If row.RowType = DataControlRowType.DataRow Then
            row.Attributes("onmouseover") = _
              "this.style.cursor=’hand’;this.style.textDecoration=’underline’;"
            row.Attributes("onmouseout") = _
              "this.style.textDecoration=’none’;"

            ‘ Set the last parameter to True
            ‘ to register for event validation.
            row.Attributes("onclick") = _
           ClientScript.GetPostBackClientHyperlink(CustomerGridView, _
                     "Select$" & row.DataItemIndex, True)
        End If
    Next

    MyBase.Render(writer)
End Sub

This code overrides the Render method for the page. It loops through each of the rows in the GridView. It sets the onmouseover and onmouseout attributes so that the user sees that the row is clickable while moving the mouse over the grid rows.

The key attribute, however, is the onclick. Setting this attribute to GetPostBackClientHyperlink allows you to get a server-side click event on the row.

The first parameter to this method is the name of the GridView control. For this example, it is CustomerGridView.

The second parameter defines the name of the command, a "$" separator, and the command argument.

NOTE: In many examples I found, the command argument is set to row.RowIndex instead of row.DataItemIndex. This does not work if your GridView is paged because RowIndex is reset to 0 for the first item on each page.

Set the last parameter of the GetPostBackClientHyperlink method to true to register the event for validation. By setting this, you don’t have to turn off enableEventValidation.

You can then catch this event using the RowCommand.

In C#:

private void CustomerGridView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select") {
        // Get the list of customers from the session 
        List<Customer> customerList =
                 Session["Customers"] as List<Customer>;

         Debug.WriteLine(customerList[Convert.ToInt32(e.CommandArgument)].LastName);
    }
}

In C#, you also need to set up the event handler. In this example, the event handler is set up in the Page_Load event, but you could put it where it makes sense for your application.

CustomerGridView.RowCommand += CustomerGridView_RowCommand;

In VB:

Private Sub CustomerGridView_RowCommand(ByVal sender As Object, _
      ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
            Handles CustomerGridView.RowCommand
    If e.CommandName = "Select" Then
        ‘ Get the list of customers from the session
        Dim customerList As List(Of Customer)
        customerList = TryCast(Session("Customers"),  _
                                 List(Of Customer))

        Debug.WriteLine(customerList(CType(e.CommandArgument, Integer)).LastName)
    End If
End Sub

This code first gets the customer list from the session. You can get the GridView information from wherever you have it defined, such as the ViewState. A Debug.WriteLine statement demonstrates how to access the CommandArgument. In a real application, you would use the CommandArgument to display the Review/Edit page for the selected customer.

Use this technique any time you want to handle a click event on an ASP.NET GridView row.

Enjoy!

ASP.NET: Displaying a Second Window with JavaScript

Filed under: ASP.NET,C#,VB.NET @ 11:34 am

In your ASP.NET application, you may want to allow a user to view some additional information without leaving the page that they are on. For example, you may want to display the current window and show some help text in a new window. Or you may want to display the concert ticket order page and allow the user to view the seating chart for the arena in a new window.

Though you can display a new window with HTML, doing it with JavaScript gives you more control over the window. To create a window with JavaScript, use the following code:

In JavaScript :

<script type="text/javascript">
<!–
   var winNew
   function OpenWindow(sURL,sName)
   {
      winNew = window.open(sURL,sName);
   }
–>
</script>

With JavaScript, you have control over the location and size of the window and whether to include the toolbar, location, scrollbars, and so on. Add the desired attributes to the open command to achieve your desired look:

In JavaScript :

winNew = window.open(sURL, sName,
  "toolbar=no, location=no, scrollbars=yes, width=600, height=300,
   top=400, left=300");

Notice that all of window attributes are in one string parameter.

To link to a new window, call the OpenWindow function in the a (anchor) element of your HTML as follows:

In HTML:

<a href="javascript:OpenWindow(‘CourseList.htm’,’CourseList’);">
    View a list of our courses
</a>

To be a good citizen, close the new window when you no longer need it. Here is a function that closes the window:

In JavaScript :

function CloseWindow()
{
   if (winNew && !winNew.closed)
   {
      winNew.close();
   }
}

This code only closes the window if a new window exists and it is not already closed. This type of coding prevents errors in your JavaScript.

You may want to call this function from a button that the user can select, or from the unload event for the page so the new window is closed when the user leaves the page:

In HTML:

<body onunload="CloseWindow()">

Use this technique any time you want to open a second window from your HTML page.

(Based on an except from "Doing Web Development: Client-Side Techniques".)

Enjoy!

ASP.NET: GridView and Business Objects

Filed under: ASP.NET,C#,VB.NET @ 12:53 am

Most ASP.NET GridView control examples demonstrate using the GridView with a SQLDataSource. But in some cases, you may want to use your own business objects instead.

One way to achieve this goal is to use the ObjectDataSource as shown in MSDN here.

Another option is to simply bind the GridView directly to your business objects without using a DataSource control.

The example presented in this post uses business objects you build yourself. These "home made" business objects are often referred to as POCO, or "plain old CLR objects". Use the techniques presented in this post any time you want to use your business objects in a GridView without using a DataSource control.

Prerequisites

First, we need some business objects. This example uses a Customer class that defines a single customer, and a Customers (plural) class that returns a generic list of customers.

In C#:

public class Customer
{
    public int CustomerId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string EmailAddress { get; set; }
}

public class Customers
{
   public static List<Customer> Retrieve()
   {
      List<Customer> custList = new List<Customer>
                    {new Customer()
                          { CustomerId = 1,
                            FirstName="Bilbo",
                            LastName = "Baggins",
                            EmailAddress = "bb@hob.me"},
                    new Customer()
                          { CustomerId = 2,
                            FirstName="Frodo",
                            LastName = "Baggins",
                            EmailAddress = "fb@hob.me"},
                    new Customer()
                          { CustomerId = 3,
                            FirstName="Samwise",
                            LastName = "Gamgee",
                            EmailAddress = "sg@hob.me"},
                    new Customer()
                          { CustomerId = 4,
                            FirstName="Rosie",
                            LastName = "Cotton",
                            EmailAddress = "
rc@hob.me"}};
      return custList;
   }
}

In VB:

Public Class Customer

    Private _CustomerId As Integer
    Public Property CustomerId() As Integer
        Get
            Return _CustomerId
        End Get
        Set(ByVal value As Integer)
            _CustomerId = value
        End Set
    End Property

    Private _FirstName As String
    Public Property FirstName() As String
        Get
            Return _FirstName
        End Get
        Set(ByVal value As String)
            _FirstName = value
        End Set
    End Property

    Private _LastName As String   
    Public Property LastName() As String
        Get
            Return _LastName
        End Get
        Set(ByVal value As String)
            _LastName = value
        End Set
    End Property

    Private _EmailAddress As String
    Public Property EmailAddress () As String
        Get
            Return _EmailAddress
        End Get
        Set(ByVal value As String)
            _EmailAddress = value
        End Set
    End Property
End Class

Public Class Customers

    Public Shared Function Retrieve() As List(Of Customer)
        Dim custList As New List(Of Customer)
        custList.Add(New Customer With {.CustomerId = 1, _
                                        .LastName = "Baggins", _
                                        .FirstName = "Bilbo", _
                                        .EmailAddress = "bb@hob.me"})
        custList.Add(New Customer With {.CustomerId = 2, _
                                        .LastName = "Baggins", _
                                        .FirstName = "Frodo", _
                                        .EmailAddress = "fb@hob.me"})
        custList.Add(New Customer With {.CustomerId = 3, _
                                        .LastName = "Gamgee", _
                                        .FirstName = "Samwise", _
                                        .EmailAddress = "sg@hob.me"})
        custList.Add(New Customer With {.CustomerId = 4, _
                                        .LastName = "Cotton", _
                                        .FirstName = "Rosie", _
                                        .EmailAddress = "rc@hob.me"})
        Return custList
    End Function

End Class

The C# code here uses auto-implemented properties to shorten the property syntax. The VB code uses the full property syntax.

In a real application, the Retrieve method would collect the data from the database. This example uses hard-coded values to make it easier for you to try this code without having to set up data access.

NOTE: Since this example includes sorting and paging, you may want to add more test data to the lists to better see the sorting and paging in operation.

Define the GridView

The next step is to define the ASP.NET GridView control. This example creates the control using HTML, but you could create the control using code if desired.

In HTML:

<asp:GridView ID="CustomerGridView" runat="server"
    AllowPaging="true" PageSize="3"
    AllowSorting="true"
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="Last Name"
            DataField="LastName" SortExpression="LastName" />
        <asp:BoundField HeaderText="First Name"
            DataField="FirstName" SortExpression="FirstName" />
        <asp:BoundField HeaderText="Email" 
            DataField="EmailAddress" SortExpression="EmailAddress" />
    </Columns>
</asp:GridView>

AllowPaging is set to true to demonstrate the paging feature. The PageSize is only set to 3 since this example includes such a small set of data. You can increase this number based on your user interface design.

AllowSorting is set to true to demonstrate the grid sorting feature. In addition, SortExpression was set for each BoundField.

AutoGenerateColumns is off so that the code can manually define the desired columns in the desired order.

Write the Code

Since there is no DataSource control in this example, you need to write code to perform the binding, sorting, and paging.

In this example, the Page_Load event calls the business object to obtain the data and performs the binding to that data.

ASP.NET generates the PageIndexChanging event when the grid is paging. So the code to handle the paging is in this event.

The Sorting event contains the code to handle the sorting. By default, the Sorting event will always request an ascending sort, so if you want your grid to sort both ascending and descending, you will need to handle that in the code. You can write the code so that when the user clicks on a column, the sort is ascending. If the user clicks on the same column again, the sort is descending. If the user clicks on a different column, the new column is sorted in ascending order.

In C#:

using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using SampleBoCSharp;

namespace SampleWebCSharp
{
    public partial class _Default : System.Web.UI.Page
    {
        public string LastSortKey
        {
            get { return ViewState["LastSortKey"].ToString(); }
            set { ViewState["LastSortKey"] = value; }
        }

        public string LastSortDirection
        {
            get { return ViewState["LastSortDirection"].ToString(); }
            set { ViewState["LastSortDirection"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Get the list of customers
                List<Customer> customerList = Customers.Retrieve();

                // Do the binding
                CustomerGridView.DataSource = customerList;
                CustomerGridView.DataBind();

                // Store in a session variable
                Session.Add("Customers", customerList);

                // Set the sort info
                LastSortDirection = string.Empty;
                LastSortKey = string.Empty;
            }

            // Set up the events
            CustomerGridView.PageIndexChanging +=
                                   CustomerGridView_PageIndexChanging;
            CustomerGridView.Sorting += CustomerGridView_Sorting;
        }

        private void CustomerGridView_PageIndexChanging(object sender,
                                              GridViewPageEventArgs e)
        {
            // Get the list of customers from the session
            List<Customer> customerList = default(List<Customer>);
            customerList = Session["Customers"] as List<Customer>;
            // Set the index
            CustomerGridView.PageIndex = e.NewPageIndex;
            // Rebind
            CustomerGridView.DataSource = customerList;
            CustomerGridView.DataBind();
        }

        private void CustomerGridView_Sorting(object sender,
                                    GridViewSortEventArgs e)
        {
            // Get the list of customers from the session
            List<Customer> customerList = default(List<Customer>);
            customerList = Session["Customers"] as List<Customer>;
            // Sort key is different, clear the last sort direction
            if (LastSortKey != e.SortExpression) {
                LastSortDirection = string.Empty;
            }
            // Perform the sort using Linq
            switch (e.SortExpression) {
                case "LastName":
                    customerList = Sort(customerList,
                                        cust=> cust.LastName);
                    break;
                case "FirstName":
                    customerList = Sort(customerList,
                                        cust=> cust.FirstName);
                    break;
                case "EmailAddress":
                    customerList = Sort(customerList,
                                        cust => cust.EmailAddress);
                    break;
            }
            LastSortKey = e.SortExpression;
            // Rebind
            CustomerGridView.DataSource = customerList;
            CustomerGridView.DataBind();
            // Store in a session variable
            Session.Add("Customers", customerList);
        }

        private List<Customer> Sort(List<Customer> list,
                Func<Customer, string> sortKey)
        {
            if (LastSortDirection == "ASC") {
                list = list.OrderByDescending(sortKey).ToList();
                LastSortDirection = "DESC";
            }
            else {
                list = list.OrderBy(sortKey).ToList();
                LastSortDirection = "ASC";
            }
            return list;
        }
    }
}

In VB:

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Public Property LastSortKey() As String
        Get
            Return ViewState("LastSortKey").ToString
        End Get
        Set(ByVal value As String)
            ViewState("LastSortKey") = value
        End Set
    End Property

    Public Property LastSortDirection() As String
        Get
            Return ViewState("LastSortDirection").ToString
        End Get
        Set(ByVal value As String)
            ViewState("LastSortDirection") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, _
             ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            ‘ Get the list of customers
            Dim customerList As List(Of Customer)
            customerList = Customers.Retrieve()

            ‘ Do the binding
            CustomerGridView.DataSource = customerList
            CustomerGridView.DataBind()

            ‘ Store in a session variable
            Session.Add("Customers", customerList)

            ‘ Set the sort info
            LastSortDirection = String.Empty
            LastSortKey = String.Empty
        End If
    End Sub

    Private Sub CustomerGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles CustomerGridView.PageIndexChanging
        ‘ Get the list of customers from the session
        Dim customerList As List(Of Customer)
        customerList = TryCast(Session("Customers"),
                                 List(Of Customer))

        ‘ Set the index
        CustomerGridView.PageIndex = e.NewPageIndex

        ‘ Rebind
        CustomerGridView.DataSource = customerList
        CustomerGridView.DataBind()
    End Sub

    Private Sub CustomerGridView_Sorting(ByVal sender As Object, 
          ByVal e As GridViewSortEventArgs) 
          Handles CustomerGridView.Sorting
        ‘ Get the list of customers from the session
        Dim customerList As List(Of Customer)
        customerList = TryCast(Session("Customers"),
                                  List(Of Customer))

        ‘ If the sort key is different, clear the last sort direction
        If LastSortKey <> e.SortExpression Then
            LastSortDirection = String.Empty
        End If

        ‘ Perform the sort using Linq
        Select Case e.SortExpression
            Case "LastName"
                customerList = Sort(customerList,
                                 Function(cust) cust.LastName)

            Case "FirstName"
                customerList = Sort(customerList, 
                                 Function(cust) cust.FirstName)

            Case "EmailAddress"
                customerList = Sort(customerList, 
                                 Function(cust) cust.EmailAddress)

        End Select
        LastSortKey = e.SortExpression

        ‘ Rebind
        CustomerGridView.DataSource = customerList
        CustomerGridView.DataBind()

        ‘ Store in a session variable
        Session.Add("Customers", customerList)
    End Sub

   Private Function Sort(ByVal list As List(Of Customer), _
     ByVal sortKey As Func(Of Customer, String)) As List(Of Customer)

        If LastSortDirection = "ASC" Then
            list = list.OrderByDescending(sortKey).ToList()
            LastSortDirection = "DESC"
        Else
            list = list.OrderBy(sortKey).ToList()
            LastSortDirection = "ASC"
        End If
        Return list
    End Function
End Class

The LastSortKey and LastSortDirection properties retain the sort criteria so that you can sort ascending or descending. The  values are stored in the ViewState so they can be retained with the other page data.

The Page_Load event calls the Retrieve method on the Customers object to retrieve the list of customers. It then sets the DataSource property of  the GridView and binds it.

NOTE: For the paging to work correctly, the GridView must be bound to a List.

The code then stores the customer list in a session variable. This is not necessary if you want to ensure that the data is fresh each time that it is sorted or paged.

Finally, it sets a default value into the LastSortKey and LastSortDirection properties so they are not null.

The PageIndexChanged event retrieves the list of customers from the session variable, sets the GridView PageIndex, and rebinds to the list.

NOTE: If you re-retrieve the customer list instead of storing/retrieving it from the session, you will need to resort it before rebinding because it will have lost any sorting.

The Sorting event retrieves the list of customers from the session variable. It then checks the last sort key and clears the LastSortDirection if the user clicked on a different column. It then performs the sort using a lambda expression.

Finally, it rebinds the GridView to the list and stores the sorted list back to the session variable.

The Sort method defined in this example takes the list and a lambda expression in as parameters, performs the sort, and returns the sorted list.

The result looks like this:

image

You can then style the grid to match your user interface design. And adding an image to show whether the column was sorted ascending or descending would also be nice.

Enjoy!

January 21, 2010

ASP.NET: Aligning Text

Filed under: ASP.NET,C#,VB.NET @ 12:40 pm

Most ASP.NET best practice guides recommend laying out pages using Div tags instead of Tables for better performance and control. With that in mind, how do you align multiple text strings in a single row?

For example, a title bar on a section of an ASP.NET page may look like this:

image

The centered title defines the content of this section of the page. The right-aligned title is a hyperlink that pops open a dialog and allows the user to set preferences for this section.

This layout would be easy enough to achieve with an HTML table. (Or a Silverlight StackPanel, but this example is for ASP.NET.) However, the goal here is to do it with Div tags.

As with most of ASP.NET, the primary way to achieve this desired result is using the "Guess and Check" technique I described in a prior post. If you missed it, here is a quick review:

  • Guess a key word or two describing what you are trying to accomplish
  • Goggle/Bing
  • Use the results to make a guess on some code (or if you look at a result and say "it can’t take 2 pages of code to accomplish this!" then repeat the prior step)
  • Run (F5) to check
  • Repeat until something miraculously works

(And if you have to support multiple browsers, you may have to repeat the last two steps for each browser.)

Using this technique, I found that the following Div tag provides the title bar shown above:

In HTML:

<div >
    <!– Empty label for blank left spacing (to center the text) –>
    <asp:Label ID="EmptyLabel" runat="server"
        Text="&nbsp;" style="float:left;width:33%;text-align:left;background-color:#BD2E26"/>
    <asp:Label ID="Label1" runat="server"
        Text="Customer Management" style="float:left;width:34%;text-align:center;background-color:#BD2E26;color:White;font-family:Calibri"/>
    <asp:HyperLink ID="PreferencesLink" runat="server"
        style="float:left;width:33%;text-align:right;background-color:#BD2E26;color:White;font-family:Calibri"
        Text="Preferences&nbsp;&nbsp;" />
</div>

The key to this technique is to divide the title bar into three segments. Set each segment using a float:left style. This stacks the segments together starting at the left.

Set the widths to 33%, 34%, and 33% to take up the full space within its container. Adjust as needed for the design effect you are trying to achieve.

Finally, set the text-align to the correct alignment for each segment. For the first segment, it does not matter because no text is displayed. For the middle segment use text-align:center and for the right segment use text-align:right.

Notice that you must provide some text in the empty label for this to work correctly. This codes just uses &nbsp; to put in a non-breaking space.

Use this technique any time you need to stack text within single line and you don’t want to use a Table.

Enjoy!

December 16, 2009

ASP.NET: Setting Focus in Modal Dialogs

Filed under: ASP.NET,C#,VB.NET @ 11:34 am

I just wanted to set focus to a TextBox on a modal dialog created using the ModalPopupExtender. How hard can it be?

As a Physics and Math major, I spent my student years using logic to attack problems and solve puzzles. So I was a little concerned when my daughters learned the "guess and check" method in Math class. How scientific or logical is that? I later came to appreciate its usefulness in some circumstances. For example, on the SAT (college entrance) tests it may be faster to "guess" each of the multiple choice items as correct and "check" them than to figure out the answer.

What does "guess and check" have to do with ASP.NET? Often it seems that there is no obvious solution to accomplish a specific design requirement. There is no obvious control property, method call or programming logic that achieves the desired result. The "guess and check" method is the only way to go:

  • Guess a key word or two describing what you are trying to accomplish
  • Goggle/Bing
  • Use the results to make a guess on some code
  • Run (F5) to check
  • Repeat for several hours until something miraculously works

This was definitely the case for what seemed like such a simple task: set the focus to a control in a modal dialog. It’s just control.focus(), right? Yes, but where would you put this code?

The problem here is that the modal dialog is initially hidden. You can’t set focus to the control when the page is loaded. Rather, you need to set the focus when the modal dialog is shown. There are no onShown or onVisible attributes for a panel/div/span. So on to "guess and check".

Because the vast majority of the sample code I found via Bing that was supposed to provide a solution for this did not work (at least not for me), here is a solution that did work.

1) Follow the steps here to define a modal dialog on one of your Web pages.

2) Add the BehaviorId attribute to the ModalPopupExtender in the ASP.NET page. The BehaviorId provides a mechanism to access the extender from script code.

In HTML:

<!– Define the modal dialog –>
<asp:ModalPopupExtender ID="SecurityQuestionModalPopupExtender" runat="server"
  BehaviorID="SecurityQuestionModalBehavior"
  TargetControlID="SecurityQuestionLink"
  PopupControlID="SecurityQuestionModalPopup"
  CancelControlID="CancelButton"
  OnCancelScript="OnSecurityQuestionCancel();"/>

3) Add this script code to your ASP.NET page:

In java script:

<script language="javascript" type="text/javascript">
    /* On page load */
    function pageLoad() {
        var modalPopup = $find("SecurityQuestionModalBehavior");
        modalPopup.add_shown(OnPopupShow);
    }

    /* Set the focus to the correct control */
    function OnPopupShow() {
        var tb = $get("QuestionTextBox");
        tb.focus();
    }

</script>

The first function executes when the page is loaded. Since the ModalPopupExtender has a BehaviorId, you can use the $find method to find it. You can then use the add_shown method and pass it a function to call when the modal popup is shown.

The OnPopupShow function then sets the focus when the modal popup is shown by finding the desired control and setting focus to it.

The result:

image

Yea, it seems like this add_shown method was pulled out of thin air. Without Bing, there is no way I would have found this method. It is not in any documentation I have read nor does it appear in intellisense.

The only place I was able to find any documentation (if you would call it that) is in the ModalPoupBehavior.js file provided with the Ajax toolkit source code. Is it just me or is it TOTALLY LAME to have to read the Ajax source code to get something this basic to work?

NOTE: Most of the examples I found during my "guess and check" used add_showing instead of add_shown. This generated the following error during my "check" phase: "Can’t move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus."

If you need to write this code in VB/C# code behind instead of javascript in the ASP.NET page, see this link.

Use this technique any time you need to set focus to one of the controls on a modal dialog. And use the "guess and check" method every time you need to do anything beyond the basics with ASP.NET.

Enjoy!

December 15, 2009

ASP.NET: Clearing Modal Dialogs

Filed under: ASP.NET,C#,VB.NET @ 3:08 pm

In my last post, I demonstrated how to build a modal dialog using the AJAX control in ASP.NET. As soon as you add validation to your modal dialog you will find the same issue that I did: Cancelling the dialog does not clear the content or validation messages.

Take this user scenario for example.

1) User clicks Security Question to open the security question dialog.

2) User enters the question, but no answer and clicks OK.

image

3) User clicks Cancel.

image

4) Sometime later on this same page, the user clicks Security Question again.

image

Notice that the entered text and validation message are still there.

Yes, this may be a far fetched scenario, but as you work with the ModalPopupExtender, you will see this issue come up again and again. In some cases, leaving the prior entered value may be OK. But in other cases, you want to open this modal dialog in a reset state.

There are several ways to attack this problem and this post covers two of them:

  • Use server-side code in the Cancel button to clear the dialog.
  • Use client-side script for the Cancel button to clear the dialog.

Using Server-Side Code

Using server-side script requires the following steps:

1) Remove the CancelControlID from the ModalPopupExtender control in the ASP.NET code. This allows the Cancel button to be processed by the server-side code.

2) Add a Click event handler for the Cancel button. Follow a technique similar to the OK button in my last post to set up the event handler.

NOTE: For C# ONLY, be sure to add the onclick attribute:

<asp:Button ID="CancelButton" runat="server"
    Text="Cancel" ToolTip="Click to cancel any changes" 
    CausesValidation="false"
    onclick="CancelButton_Click"/>

3) Add the desired code to the Cancel button Click event handler in the code behind file.

In C#:

Be sure to set a reference to the System.Web.UI namespace.

protected void CancelButton_Click(object sender, EventArgs e)
{
    // Clear the validators
    foreach (IValidator ctrl in Validators)
    {
        ctrl.IsValid=true;
    }

    // Clear the control contents
    QuestionTextBox.Text = String.Empty;
    AnswerTextBox.Text = String.Empty;

    //Close the popup
    SecurityQuestionModalPopupExtender.Hide();
}

In VB:

Private Sub CancelButton_Click(ByVal sender As Object, _
         ByVal e As System.EventArgs) Handles CancelButton.Click
    ‘ Clear the validators
    For Each ctrl As IValidator In Validators
        ctrl.IsValid = True
    Next

    ‘ Clear the control contents
    QuestionTextBox.Text = String.Empty
    AnswerTextBox.Text = String.Empty

    ‘ Close the popup
    SecurityQuestionModalPopupExtender.Hide()
End Sub

This code first clears any validation controls. It then clears the text from both of the TextBoxes. Finally, it closes the modal dialog.

The down side of this approach is that it is server side. This means that it requires hitting the server to clear the dialog. A more performant approach is to use client-side scripting.

Using Client-Side Code

Using client-side script requires the following steps:

1) Ensure the ModalPopupExtender has both the CancelControlID and OnCancelScript attributes set:

<asp:ModalPopupExtender ID="SecurityQuestionModalPopupExtender"
   runat="server"
  TargetControlID="SecurityQuestionLink"
  PopupControlID="SecurityQuestionModalPopup"
  CancelControlID="CancelButton"
  OnCancelScript="OnSecurityQuestionCancel();"/>

The OnCancelScript attribute must be set to the name of the javascript function defined in the next step.

2) Write the javascript code:

<script language="javascript" type="text/javascript">
    /* On cancel of the Signin dialog, clear the fields */
    function OnSecurityQuestionCancel() {
        $get("QuestionTextBox").value = "";
        $get("AnswerTextBox").value = "";
        $get("QuestionValidator").innerHTML = "";
        $get("AnswerValidator").innerHTML = "";
    }
</script>

For this example, I added this javascript code to the head tag of the ASP.NET page.

This code uses the Ajax $get shortcut for the getElementById to find both TextBoxes and both validators. It then clears them. Because this is javascript, it has to work with the controls that are rendered. For the TextBox controls, these are HTML input controls that have a value attribute. For the validation controls, these are the HTML span controls. To clear those, you need to clear the innerHTML attribute.

Use one of these techniques any time you want to clear a modal dialog.

Enjoy!

ASP.NET: Modal Dialogs

Filed under: ASP.NET,C#,VB.NET @ 2:27 pm

There are often times when your Web design includes a modal dialog. For example:  a login form, a dialog for entering basic information, a search form, or a data entry form. This post covers how to build a modal dialog in ASP.NET.

There are several advantages to using a modal dialog instead of another Web page:

  • The user does not have to navigate away from the current page. This allows the user to focus on the main information, yet enter criteria or other parameters in a modal dialog.
  • The code has better control over the dialog operations. That is to say that the user must provide some response to the modal dialog. However, the user can still navigate to another page or close the browser.

I mentioned in a recent post that after being away from ASP.NET for a while, I was surprise at how little had changed. But there is one area where ASP.NET has changed significantly: AJAX. If you have not downloaded the ASP.NET AJAX  toolkit, check it out here.

This post focuses on the ModalPopupExtender control that is part of the AJAX toolkit. In this example, the user sets a security question and answer in a modal dialog. If the user clicks on the Security Question link in the upper right corner, the Security Question modal dialog appears for entry of the question and answer.

image

As with most modal dialogs, this one implements validation. If the user clicks on OK without entering the required data, validation messages appear:

image

I wrote this example in both VB and C#. But since the only line of code that is different is the Page tag that defines the language, I am only showing the ASP.NET code one time.

In HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SampleWebCSharp._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Sample Web Page</title>
</head>

<body style="background-image: url(Images/Gradient2.jpg);background-repeat: repeat-x;">
    <form id="form1" runat="server">
        <asp:ScriptManager ID="sm" runat="server"/>

        <!– Right side Link bar –> 
        <div style="text-align:right"> 
            <!– Signin Area –> 
            <asp:HyperLink ID="SigninLink" runat="server" 
                style="color:White;cursor:pointer" 
                ToolTip="Click to sign into the application" 
                Text="Sign in" /> 
            <label style="margin-left:8px;
                   margin-right:8px;color:White">|</label> 
            <asp:HyperLink ID="SecurityQuestionLink" 
                runat="server" 
                style="color:White;cursor:pointer" 
                ToolTip="Click to set the security question" 
                Text="Security Question" /> 
        </div> 
         <!– Security Question Popup –> 
        <asp:Panel ID="SecurityQuestionModalPopup" 
            runat="server" 
            Style="display:none;width:300px;
                   background-color:White; 
                   border-width:3px;border-style:solid;
                   border-color:#B92217;color:#7C1810;
                   padding:3px;"> 
            <asp:Label ID="Label1" runat="server" 
                Text="Security Question" width="300px"/><br /> 
            <br /> 
            <table style="width: 100%;"> 
                <tr> 
                    <td align="right"> 
                        <asp:Label ID="Label2" 
                         runat="server" 
                         Text="Question:"/> 
                    </td> 
                    <td> 
                        <asp:TextBox ID="QuestionTextBox" 
                         runat="server" Width="150"/> 
                    </td> 
                </tr> 
                <tr> 
                    <td align="right"> 
                        <asp:Label ID="Label3" 
                         runat="server" 
                         Text="Answer:"/>
                    </td> 
                    <td> 
                        <asp:TextBox ID="AnswerTextBox" 
                         runat="server" Width="150"/> 
                    </td> 
                </tr> 
                <tr> 
                    <td colspan="2"> 
                        <asp:RequiredFieldValidator 
                          ID="QuestionValidator" 
                          runat="server" 
                          ControlToValidate="QuestionTextBox" 
                          Display="Dynamic" 
            ErrorMessage="Please enter your security question.<br/>"/> 
                      <asp:RequiredFieldValidator 
                          ID="AnswerValidator" 
                          runat="server"
                          ControlToValidate="AnswerTextBox" 
                          Display="Dynamic" 
            ErrorMessage="Please enter the answer to your security question.<br/>"/> 
                    </td> 
                </tr> 
           </table> 
            <br /> 
            <!– Bottom Buttons –> 
            <div style="text-align:right"> 
                <asp:Button ID="OKButton" runat="server" 
                Text="OK" 
                ToolTip="Click to save the entered question/answer"/>  
                 <asp:Button ID="CancelButton" runat="server" 
                Text="Cancel"

CausesValidation="false"
                ToolTip="Click to cancel any changes"/> 
            </div> 
        </asp:Panel>

        <!– Define the modal dialog –> 
        <asp:ModalPopupExtender 
            ID="SecurityQuestionModalPopupExtender" runat="server" 
            TargetControlID="SecurityQuestionLink" 
            PopupControlID="SecurityQuestionModalPopup" 
            CancelControlID="CancelButton" /> 
    </form>
</body>
</html>

Notice at the very top of the code the Register tag registers the Ajax Control Toolkit. This line is added to your code automatically if you drag an Ajax control onto your WebForm.

The body tag uses a gradient image as shown in this prior post.

The ScriptManager control manages all of the Ajax features and is required on any page that uses Ajax controls.

The first div element contains the code to display the links in the upper right corner. No special code is required on these elements. The HyperLink control does not have an attribute to display the modal dialog. Rather, the ModalPopupExtender identifies the control that will cause it to popup. (More on this later in this post.)

The Panel control contains all of the controls that appear in the modal dialog. It also defines the style of the popup including its background color, foreground color, and border. Notice that the display style is set to none. This ensures that the popup does not display when the page is first rendered.

In this example, the modal dialog contains a title at the top, a table to layout the Labels and TextBoxes in the middle, and OK and Cancel buttons on the bottom. Notice that the Cancel button has its CausesValidation attribute set to false. This ensures that pressing the Cancel button won’t perform the validation and display the validation messages.

An additional row in the table provides an area to display validation messages. The validation controls have their Display attribute set to Dynamic so that space is not allocated to the message text unless there is a validation error.

Finally, the key part of this code: the ModalPopupExtender. The key attributes of this control in this example are:

  • TargetControlID: Id of the control that causes display of the modal dialog. In this case, it is the Security Question Hyperlink control at the top right of the page.
  • PopupControlID: Id of the control that is the modal dialog. In this case, it is the Panel control.
  • CancelControlID: Id of the button on the modal dialog that causes a cancel operation. By default, this closes the modal dialog.

Notice that the OKControlID attribute is not set for this control. By default, setting the OKControlID also closes the modal dialog, so validation messages won’t appear.

If you don’t set the OKControlID attribute, you can instead write code for the OK button in the code behind. This allows for the display of the validation messages. You can also perform processing, such as additional server-side validation or saving the entered values.

In C#:

using System;

namespace SampleWebCSharp
{
    public partial class _Default : System.Web.UI.Page
    {

        protected void OKButton_Click(object sender, EventArgs e)
        {
            // Do any additional processing, such as saving the values

            //Close the popup
            SecurityQuestionModalPopupExtender.Hide();
        }

    }
}

In VB:

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Private Sub OKButton_Click(ByVal sender As Object, _
               ByVal e As System.EventArgs) Handles OKButton.Click
        ‘ Do any additional processing, such as saving the values

        ‘ Close the popup
        SecurityQuestionModalPopupExtender.Hide()
    End Sub
End Class

NOTE: The technique you use to set up the events is very different in VB than in C#.

In C#:

  • Double-click on the control.
    In this example, this is not an easy task because the panel containing the button is hidden. So to use this method, you would need to temporarily make the panel not hidden, double-click on the button, and make the panel hidden again.
  • OR, manually type in the event signature in the code behind file.

With the first technique, Visual Studio automatically changes the Button attributes in your ASP.NET code as follows:

<asp:Button ID="OKButton" runat="server"
     Text="OK" ToolTip="Click to save the entered question/answer"
     onclick="OKButton_Click"/>

With the second technique, you need to add the onclick attribute yourself.

In VB:

  • Double-click on the control.
    Again, not so easy because the control is hidden.
  • OR, open the code behind file and use the two ComboBoxes at the top of the code editor. Select the control from the first ComboBox on the left. Select the event from the second ComboBox on the right. This is the best technique to use in this example.

NOTE: VB does NOT require a change in the ASP.NET code.

Use this technique any time you want to display a modal dialog from your Web page.

Enjoy!

« Previous PageNext Page »

© 2021 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs