Saturday, May 07, 2011

C# - Container Controls 3 - SplitContainer


1. Introduction


A "Split Container" is a combination three components.  Panel1 and Panel2 separated either horizontally and vertically by a splitter.  A split container is useful to create your favorite windows explorer-like user interface. To set the properties for the panels you should click the panel portion of the container. To select the entire container, click on the splitter. You can set a different set of properties for the panels on both sides of the splitter.

The splitter helps to resize the panels and...  Oh!!! All right I no need to explain, all of us know how windows explorer user interface works.

2. About the Sample


Have a look at the below screenshot:



The top area shows the Splitter container. The panel on the left side (Panel 1) is placed with a set of controls. The Panel on the right side is filled with a listbox control. You can adjust the width of the splitter by adjusting the value in the "Updown Control". Similarly, you can set the minimum size for the panel 1 by adjusting the value in the second updown control. The minimum size restricts resizing of the panel1 by moving the splitter after a certain limit.

The Close Action Panel checkbox collapses the panel1 when it is checked and brings it back when it is unchecked. The radio buttons help to split the panels vertically or horizontally.

3. Designing the Form layout shown above


1) First, drag and drop the Panel control on the form from the Container group of control. The panel appears as shown below:



2) Using the arrow shown above move it to the bottom of the form.

3) When the control is still in selected state, access the properties, and select the dock property by clicking the down arrow on the value. From the displayed context dialog, click the down button shown as a red box in the below picture:



This step makes the panel docked to the bottom of the form and when you resize the form the bottom panel goes with the bottom edge.

4) Now drag and drop the "SplitContainer Control" to the form in the unoccupied area that is in the area where the previously placed panel not exists. You can find this control also in the containers group of control in the toolbox as shown in the below picture.



Once you are done the form looks like what is shown below (Note I just set the background color for the panel in the bottom, to differentiate it from the Split container):



In the above form, there are three panels. First a standalone panel is in the bottom of the form and other two panels on the top of the form came from the Split Container Control. This is the basic layout. For this split, the container sets the "Dock Property" to Fill.

5) Now you can refer the attached sample to place all other controls on the specific panels. To place a control on the specific panel (One of three) drag the control from the toolbox and drop it to the panel in which you want to place the control.

4. Adding and removing items


This is straight forward, the click event handler for the add item button will add the text entered in the text box to list box in panel 2. The remove item button will remove the selected item in the list box at panel 2 of the container. Below is the code:

//Split 01: Add the items to the list box
private void btnAdd_Click(object sender, EventArgs e)
{
    List.Items.Add(txtName.Text);
}

//Split 02: Remove item from list box
private void btnRemove_Click(object sender, EventArgs e)
{
    List.Items.RemoveAt(List.SelectedIndex);
}

5. SplitterWidth of SplitContainer


Increasing the value or decreasing the value of the splitter width up-down control can adjust the splitter width. "SplitterWidth Property" of the split container adjusts the splitter width. In the sample, I set the maximum of 10 for the Up-down control through a property. So the maximum splitter width that can be set to the splitter in this sample is 10. The below screen shot shows a splitter width of 8:



Below is the code for it:

//Split 03: Change the Splitter width
private void udSplitWidth_ValueChanged(object sender, EventArgs e)
{
    splitContainer.SplitterWidth = (int) udSplitWidth.Value;
}

6. Split vertical or horizontal


When we click the horizontal radio button the split container’s panel are split horizontally. To split it vertical again the split vertical radio button should be checked. Below is the screen shot:



The code just sets the "Orientation Property" to the control to a constant by taking it from the Orientation enumeration. Below is the code for it:

//Split 04: Split Vertically or Horizontally
private void rdSplitVerticle_CheckedChanged(object sender, EventArgs e)
{
    if (rdSplitVerticle.Checked == true )
        splitContainer.Orientation = Orientation.Vertical;
    else
        splitContainer.Orientation = Orientation.Horizontal;
}

7. Collapsing the panel and Panel minimum size

Split container control allows collapsing the panel. But it should either panel1 or panel2. Setting minimum size (Again only one panel of the split container can have the minimum size) does allow the user to shrink the panel beyond that size. The properties "Panel1MinSize" and "Panel1Collapsed" are accessed at runtime to do the collapsing of panel 1 and restricting the size reduction of panel1 by moving splitter to a certain limit. Below is the code for it:

//Split 05: Set Minimum size for Panel 1
private void udp1Minsize_ValueChanged(object sender, EventArgs e)
{
    splitContainer.Panel1MinSize = (int)udp1Minsize.Value;
}

//Split 06: Set Minimum size for the panel
private void frmSplitter_Load(object sender, EventArgs e)
{
    splitContainer.Panel1MinSize = 100;
}

//Split 07: Collapse Panel 1
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBox1.Checked == true)
        splitContainer.Panel1Collapsed = true;
    else
        splitContainer.Panel1Collapsed = false;
}


Note: The attached solution is in VS2005. If you have the latest version, Say “Yes” to the Conversion dialog.

Source Code : Download

Monday, May 02, 2011

ASP.Net - Using Calendar Control and Importance of DayRender Event


1. Introduction


The Calendar Control in ASP.net allows you to pick a date. Why we need a control like this for picking a date that involves navigation when I easily type the date in a specific format in a textbox? Well, so the Calendar control has usually used a calendar and the control is useful when the user wants to do some kind of date scheduling by knowing the Day of the date, weekdays and holidays etc., Now if I ask that a text box control provides all these information, you will answer No.

So, the control is useful on the above-said situation and it is not much useful when you placed it to specify the date of birth for a person. It is upon the developer to decide when to use the control.

When you place a Calendar control on the ASP.net page, the Initial appearance does not look great. But it still does the basic job selecting a date. We will explore some properties which will make the control look pleasing and then we will move to the coding part of it.

Below is the Initial appearance of the control when you placed it in the ASP.net page without setting any properties:




2. Setting up the control


Below are the important properties that will be useful to customize the control the way we want.

The ShowHeader Property allows hide/show of the heading of the control. In the above control, the heading is the weekdays displayed below the control Title.

The ShowTitle Property is useful to control showing or hiding the Title of the calendar. The title of the Control shows the Year and present month. And each numbered tile in the control represents the Day. If you need you can display grid lines separating each tile from others using the ShowGridLines property.

The properties NextMonthText, PreviousMonthText is used to set the text or image for the next or previous month navigations. In the above control, the navigation text is set to <= and >=. These texts are actually a link that moves the month in the calendar control backwards or forward. You can also specify an image using the Img Src HTML tag. In the sample, I used the images, have a look at these property values in the downloaded sample.

The SelectionMode property allows how many days can be picked one at a time. The values and the selection behaviour is given below:
Day: You can pick only one date.
Dayweek: You can pick a single day or an entire week. An arrow will be displayed for each week for making the selection. The Selection Link text can be changed to image using the property SelectWeekText

DayWeekMonth: You can pick a single day or Entire week or entire month. In addition to Arrows for Weeks, you will get one more arrow in the top corner to select the entire month. The selection link text can be changed or set to an image using the property SelectMonthText

In the Sample,
I set the SelectionMode property to DayWeekMonth.
The properties NextMonthText, PreviousMonthText, SelectWeekText, SelectMonthText are used to change the arrow keys into images. Have a look at these property values in the sample. Below is the example for NextMonthText from the sample:
<img src='images/NMonth.ico' border=0>

You can set different Background color, foreground color, fonts etc to each part of the control by accessing the following properties:
1) DayHeaderStyle : Day header is the one that displays weekdays name
2) DayStyle: Set style for each normal days in the calendar
3) NextPrevStyle: Set style for the Next and previous month
4) OtherMonthStyle: When a month is displayed in the calendar, there are days that comes from the previous and/or next months. This property sets style for those
5) SelectedDayStyle: Sets the style for the currently selected Day
6) SelectorStyle: Sets the style for the Month and week selectors
7) TitleStyle: Sets the style for the title.
8) TodayDayStyle: Style for the Today’s day
9) WeekDayStyle: Sets style for the Week Days Style.

By setting the above properties, you can make a big difference to the Calendar control, Have a look at these property values in the attached sample application. You no need to look property values for all the 9 properties, just have a look at the one to get an idea.

Below is the customized Calendar control from the Sample:




3. About the Sample


The calendar control displayed above is formatted to have a better look. The arrows in the title allow you to navigate between the months. The diagonal arrow is to select all the dates in the present month. Horizontal arrow will select the entire week. You can also select a single day by clicking on it. Today’s day is highlighted in light green color. The special days (Can be anything, in this sample it is a holiday) are shown in dark green. Days that is not part of the present month is shown in green color. Weekdays are shown in different color.

Below the calendar control is a Panel and Label to display the selected dates. The check boxes allow to show or hide the visual appearance of the calendar control say, Grid Lines, Calendar header and Calendar title.

Look at the screen shot of the sample page shown below:




4. Controlling the Header, title & Grid Lines


At runtime, the property already discussed in section two is set to control the visibility of the Calendar header, Calendar visibility and grid lines separator for the days. Note that once you turn off the grid lines, the BroderStyle property of the nine calendar style (specified in section two) becomes effective. Below is the code for setting the Boolean properties at runtime:

//Calendar 01: Show/Hide Header
protected void chkHeader_CheckedChanged(object sender, EventArgs e)
{
    Calendar.ShowDayHeader = chkHeader.Checked;
}

//Calendar 02: Show/Hide GridLine in the Calendar Control
protected void chkGridLines_CheckedChanged(object sender, EventArgs e)
{
    Calendar.ShowGridLines = chkGridLines.Checked;
}

//Calendar 03: Show/Hide Calendar Title
protected void chkTitle_CheckedChanged(object sender, EventArgs e)
{
    Calendar.ShowTitle = chkTitle.Checked;
}

During the page load event, all the check boxes are set in the checked state. Also, the calendar’s header, title, gridlines are turned on. Below is the code for it:

//Calendar 04: Set the Default Properties
protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack == false)
    {
        Calendar.ShowDayHeader = true;
        Calendar.ShowGridLines = true;
        Calendar.ShowTitle = true;
        chkGridLines.Checked = true;
        chkHeader.Checked = true;
        chkTitle.Checked = true;
    }
}

5 Selection Changed Event


Remember that the Selection Mode property of the calendar control was set to DayWeekMonth. So the control allows you select multiple dates by Week selector (Horizontal Arrows) and the Month Selector (Diagonal Arrow). You can also select a single day. In all these cases selection changed event is fired. The handler for that event is the perfect place for listing the selected date. Below is the code for it:

//Calendar 05: Get the Selected Date(s) and display it in the Label
protected void Calendar_SelectionChanged(object sender, EventArgs e)
{
    string date_str = "";
    int count = 0;

    foreach (DateTime dt in Calendar.SelectedDates)
    {
        count++;
        date_str = date_str + "Selected Date #" + count.ToString() + ": " +
            dt.ToShortDateString() + "<br/>";
    }

    lblDisplay.Text = date_str;
}

Note the usage of the <br/> as the ASP.Net label control does not interpret the Newline character properly.

6. Marking the Special Days and DayRender Event


Marking the special days is a kind of action that should be tied with the month navigation. That’s how we will see it initially. But there is an event for this task. The event is DayRender. The event is fired when each Day in the calendar control is drawn. So the handler can make use of the passed-in event argument to control the display of the Day part of the calendar control.

From the passed-in event argument, you can get the CalendarDay and TableCell objects. CalendarDay can be accessed by Day property and TableCell can be accessed by the Cell property of the event argument. From the CalendarDay object, you can know the date it belongs and all parts of the date. With TableCell object you can control the visual attributes of the single day. Here we are setting the special day using the TableCell property, and to know whether the cell belongs to the special day we need the CalendarDay.

Below is the code for the DayRender and I set a special day for the month of April only. Change the logic to set it for the entire year and I just want to show an example only here.

//Calender 06: When displaying the Day part of the control, make sure to adjust
//              the Day portion of the calendar control to dsplay special date.
//              Let me do it for April 5,14,18 as holiday. For full year you should
//              apply you own logic. Use a string manipulation or 2D array to do it
//              efficiently.
protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
{
    //Display the date differently when it is a holiday
    if (e.Day.Date.Month == 4)
    {
        if (e.Day.Date.Day == 5 || e.Day.Date.Day == 14 || e.Day.Date.Day == 18)
        {
            e.Cell.ForeColor = Color.Azure;
            e.Cell.BackColor = Color.Green;
            e.Cell.Font.Bold = true;
        }
    }
}

7. Closure


ASP.net calendar control does not support year wise navigation. To do so, you should derive your own class. So make sure before using it. If you provide the same above control to your user for selecting their date of birth, they will beat your manager.

8. How Do I open the Attached Project?


1) Download the attached zip file
2) Extract it to a folder
3) Open visual studio 2005
4) Click the menu item File|Open|Web site
5) Select the Extracted Folder

Note: The Attached solution is created in visual studio 2005. If you have the latest version say yes to the conversion wizard

Source Code : Download
Like this site? Tell it to your Firend :)