January 2010 - Posts
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.
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!
A common requirement with an XML file is to find a particular node. If you are targeting the .NET framework 3.5 or higher, you can find the node using Linq to XML or by using Lambda expressions.
As with many of my prior XML examples, the XML string is as follows:
<States>
<State name="Wisconsin">
<Regions>
<Region name="Milwaukee">
<Area name="Mukwanago"/>
<Area name="Germantown"/>
</Region>
<Region name="Fox Valley">
<Area name="Oshkosh" />
<Area name="Appleton" />
</Region>
</Regions>
</State>
</States>
The code to find the node for the Milwaukee region is as follows:
In C#:
// Be sure to set a reference to System.Core and System.Xml.Linq
XElement states = XElement.Load("testXML.xml");
// Using LINQ
XElement foundNode;
var query = from XElement r in states.Descendants("Region")
where r.Attribute("name").Value == "Milwaukee"
select r;
foundNode = query.FirstOrDefault();
// Using Lambda expressions
foundNode = states.Descendants("Region").
Where(r => r.Attribute("name").Value ==
"Milwaukee").FirstOrDefault();
In VB:
' Be sure to set a reference to System.Core and System.Xml.Linq
Dim states As XElement = XElement.Load("testXML.xml")
' Using LINQ
Dim foundNode As XElement
Dim query = From r As XElement In states...<Region> _
Where r.@<name> = "Milwaukee"
foundNode = query.FirstOrDefault()
' Using Lambda expression
foundNode = states...<Region>.Where(Function(r) r.@<name> = _
"Milwaukee").FirstOrDefault
This code first loads the XML file containing the XML. The next set of code can be done using LINQ or using Lambda expressions. Use either one, but not both. :-)
The C# code uses the XElement properties and methods. The VB code uses XML literals.
NOTE: The XElement properties and methods work in VB as well.
Enjoy!
NOTE: This post was created based on a prior post that included both finding a node and adding new nodes. This post separates the first step to provide a more straightforward example.
You can document your classes, properties, methods, and so on using XML tags. I'm sure all developers know this at this point, but did you know that you can modify the set of valid tags?
If you are not familiar with XML Documentation Comments (or just XML Comments), you create them differently depending on the language you are using.
In C#:
On the line above the class, property, method, or whatever you are documenting, type three forward slashes.
///
public List<Customer> Retrieve(int Id)
Visual Studio automatically inserts the appropriate XML tags:
/// <summary>
///
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public List<Customer> Retrieve(int Id)
In VB:
On the line above the class, property, method, or whatever you are documenting, type three apostrophes.
'''
Public Function Retrive(ByVal id As Integer) As List(Of Customer)
Visual Studio automatically inserts the appropriate XML tags:
''' <summary>
'''
''' </summary>
''' <param name="id"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function Retrive(ByVal id As Integer) As List(Of Customer)
You can then build technical documentation of your API from the XML comments.
In C#:
1. Double-click on Properties for the project in the Solution Explorer.
2. Click on the Build tab.
3. Check the "XML document file" checkbox and ensure that a file name is specified.
4. Build your project.
All of the XML comments are generated into one XML file.
In VB:
Generating the XML documentation is on by default. To check it:
1. Double-click on My Project for the project in the Solution Explorer.
2. Click on the Compile tab.
3. Check the "Generate XML documentation file" checkbox.
The XML file is generated in the bin\Debug folder for the project.
You can use a product such as SandCastle to generate your technical documentation from these comments.
But what if you want more or different tags than those that are provided? IF YOU ARE USING VB.NET you can do just that.
NOTE: As far as I have seen, this technique is not available in C#.
In VB:
Locate your XML Comment tag file. Mine was here:
C:\Documents and Settings\Deborah\Application Data\Microsoft\VisualStudio\9.0\VBXMLDoc.xml
If you don't have this file, you can create it following the instructions defined here.
This file contains the definition of the valid XML tags used in XML Comments. You can then add to the contents of this file or edit it as you desire.
For one of my projects, we wanted to add an edit history to each class that included the date, the developer's name, and a description. So I added the following to the Class code element:
<CodeElement type="Class">
<Template>
<summary/>
<remarks/>
<editHistory date="" developer=""/>
</Template>
<CompletionList>
<include file="" path=""/>
<permission cref=""/>
<remarks/>
<summary/>
<editHistory date="" developer=""/>
</CompletionList>
</CodeElement>
We could then create XML comments as follows:
''' <summary>
''' Manages a customer class
''' </summary>
''' <remarks></remarks>
''' <editHistory date="9/14/09" developer="DJK">
''' Added customer type.
''' </editHistory>
''' <editHistory date="10/17/09" developer="DJK">
''' Added an Email address.
''' </editHistory>
Public Class Customer
Use this technique any time you want to enhance your XML comment documentation in VB.NET.
Enjoy!
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:
The Listbox displays the first 6 items as per the Rows property. Since there are 8 items, it automatically displays the scrollbar.
Enjoy!
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!
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="BLOCKED SCRIPTOpenWindow('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!
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:
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!
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:
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=" " 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 " />
</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 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!
When Windows Presentation Framework (WPF) and Silverlight first came out, the announcements happily proclaimed that it was even easier to have your visual design team build really nice user interfaces that we, the developers, could then enhance with code. But what about the significant number of us that don't have a visual design team or even a single visual designer?
Even though we may not have had an art class since 6th grade, developers can create really nice looking Silverlight applications. And Silverlight Themes makes it easy.
NOTE: Silverlight themes are part of the Silverlight Toolkit that you can download from here.
Take this simple Silverlight page:
It looks OK. Kind of looks like a WinForms application. But it can get the job done. The user can click on Edit to edit the customer information. Or add, edit, or delete contacts for the customer. The user can also view an invoice summary or click the Open button to view the details of any invoice.
Now let's apply the Bureau Black Theme:
That looks more like a Silverlight application! Even though the functionality is exactly the same, applying a theme can make it look much nicer.
NOTE: In addition to applying the theme, some additional design features were applied to the dialogs shown in this post. For example, color and rounded corners on the page sections.
Don't like black. How about the Shiny Red Theme:
Want it more white, try the Whistler Blue Theme:
There are many more themes to choose from such as Expression Light and Rainier Purple.
Applying a theme to your page is easy. First, ensure that you have installed the Silverlight Toolkit as mentioned above. Then, if you are using Blend or Visual Studio, just drag and drop the desired theme from the toolbar to your page. This adds the appropriate references and namespaces to your code.
To theme the entire page, set the theme element around the entire page contents.
In XAML:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:bureauBlack="clr-namespace:System.Windows.Controls.Theming;assembly=System.Windows.Controls.Theming.BureauBlack"
mc:Ignorable="d"
x:Class="SampleSimpleSL.CustomerManagementUC">
<bureauBlack:BureauBlackTheme>
<Grid x:Name="LayoutRoot">
. . . [Your code here]
</Grid>
</bureauBlack:BureauBlackTheme>
</UserControl>
NOTE: When you drag and drop the theme, the designer may add a bunch of attributes to the theme tag, such as a Content attribute. Remove these or the theme may not work properly.
Though you can't see it in the above screen shots, the themes also provide interactivity effects. For example, as you move the mouse over list box items, the items are highlighted. If you move the mouse over a button, the button color changes or highlights, and so on.
For example, here I had the mouse over the Edit button when I captured the screen:
Microsoft provided an interactive page to try out the themes. You can see the interactivity effects for each of the themes here. Select Theming | Theme Browser from the panel on the left. Then click on the desired theme across the top:
Pick a theme for your application and see what a difference it can make in your visual design.
Enjoy!
Depending on how you code the XAML for a RadioButton in Silverlight, you may not be able to get it to center. If you have simple RadioButton text, this issue is not noticeable. But if you include controls like a NumericUpDown as part of the RadioButton, it is very noticeable. I would assume that this is a bug in the RadioButton control.
Here is an example:
In this example, the second bullet point is shown twice. In the first case, the radio button is not centered with the other text. In the second case it is.
In XAML:
<StackPanel Orientation="Vertical" Margin="5">
<TextBlock
HorizontalAlignment="Left" VerticalAlignment="Center"
Text="When is this process allowed?"/>
<RadioButton Margin="20,0,0,0"
Content="Always" IsChecked="True"/>
<RadioButton Margin="20,0,0,0" VerticalAlignment="Center">
<RadioButton.Content>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center"
Text="Only during the first"/>
<inputToolkit:NumericUpDown
Width="40" HorizontalAlignment="Left"
VerticalAlignment="Center" Margin="4,2,4,2"
Value="15" />
<TextBlock VerticalAlignment="Center"
Text="days"/>
</StackPanel>
</RadioButton.Content>
</RadioButton>
<StackPanel Orientation="Horizontal" Margin="20,0,0,0" >
<RadioButton VerticalAlignment="Center"
Content="Only during the first"/>
<inputToolkit:NumericUpDown
Width="40" HorizontalAlignment="Left"
VerticalAlignment="Center" Margin="4,2,4,2"
Value="15" />
<TextBlock VerticalAlignment="Center"
Text="days"/>
</StackPanel>
</StackPanel>
In the first case, the code uses RadioButton.Content to place a StackPanel with TextBlock, NumericUpDown, and TextBlock controls within the RadioButton. This way of coding the RadioButton prevents it from being centered.
In the second case, the code uses a StackPanel with a RadioButton, NumericUpDown, and TextBlock within it. In this case, the RadioButton is correctly centered.
Keep this in mind when using RadioButtons with more than simple text.
Enjoy!
If you are starting a new Silverlight project, you may want to take a look at SketchFlow. SketchFlow allows you to easily build an interactive prototype.
Building a Silverlight prototype with SketchFlow has several advantages:
- SketchFlow allows you to quickly put together a sample user interface for your Silverlight application. This saves you time and money as you start to flesh out the application user interface.
- Since it is so easy to build pages with SketchFlow, you can provide multiple choices and alternate design ideas.
- The style of the controls makes it clear that it is a prototype. (The fonts and controls look like they would if you drew them on your whiteboard.) This helps the users focus on functionality, not on the visual design.
- SketchFlow provides an easy way to hook pages together. For example, in the SketchFlow designer, you can right-click on a Log In button in a prototype login page to define the page that should be displayed after a successful log in.
- SketchFlow makes it easy to dummy up data to display in your UI.
- The SketchFlow player provides an easy way to navigate through your pages without building any code.
- Reviewers can add comments about the prototype directly from the SketchFlow player, making it easy to collect feedback.
- You can learn how to use SketchFlow in about 20 minutes.
Here is an example screen shot shown within the SketchFlow player. Notice the Map in the lower left corner. It allows you to navigate to any page of the prototype.
SketchFlow is part of Microsoft Expression Blend 3.0. However, it is not immediately obvious how to use it. Luckily, there is a set of videos that provide a quick start. Each video is around 5 minutes in length, getting you going quickly. You can find the videos here.
Enjoy!
Don't know what I was thinking to vacation in New York in January! Burrrr!
Had a great time though.
Stayed at the Marriott Marquis in Times Square and could see the New Year's Eve ball from our window:
Skated at Rockefeller Center:
(That's me in the back with the black coat.)
Saw the dinosaurs:
And Wicked:
And the ball from the World Trade Center:
The Statue of Liberty:
And some Van Gogh's:
Did I mention it was cold?
Hope you had a great holiday!