Personal notes on software development.
For Java technologies check my dedicated site

Pages

Showing posts with label ASP.NET Control. Show all posts
Showing posts with label ASP.NET Control. Show all posts

Important Properties:

  • CausesValidation [1] indicate whether or not clicking the Button should initiate the validation logic (defaults to True). For example, when the user introduced some invalid data on the form and wants to click the Cancel button. This Cancel button shouldn't listen to the validation logic and carry on the execution.
  • CommandName [2] when a Button, LinkButton, or ImageButton whose CommandName property is set is clicked from within a Repeater or DataList, the Repeater or DataList s ItemCommand event is raised. For the DataList, if the CommandName property is set to a certain (special) value, an additional event may be raised as well. This special CommandName property values include, among others:
        1. "Cancel": raises the CancelCommand event;
        2. "Edit": raises the EditCommand event;
        3. "Update": raises the UpdateCommand event;
        4. "Delete": raises the DeleteCommand event;

Related articles:
[1] - Adding Validation Controls to the DataList's Editing Interface
[2] - An Overview of Editing and Deleting Data in the DataList

Similar to the FormView, the DataList control's rendered output depends upon templates rather than BoundFields, CheckBoxFields, and so on. Unlike the FormView, the DataList is designed to display a set of records rather than a solitary one.

If we need to display multiple records from a data source we can use the GridView, the DataList or the Repeater control.

While the GridView makes it a snap to display, page through, sort, edit, and delete data, its appearance is a bit boxy (renders a row for each record in the data source, displaying the record s data fields in columns): The markup responsible for the GridView s structure is fixed it includes an HTML <table> with a table row (<tr>) for each record and a table cell (<td>) for each field.

To provide a greater degree of customization in the appearance and rendered markup when displaying multiple records, ASP.NET offers the DataList and Repeater controls. The DataList and Repeater controls render their content using templates rather than BoundFields, CheckBoxFields, ButtonFields, and so on.

Like the GridView, the DataList renders as an HTML <table>, but allows for multiple data source records to be displayed per table row. The Repeater, on the other hand, renders no additional markup than what you explicitly specify, and is an ideal candidate when you need precise control over the markup emitted.

Notes:

  • The DataList does not support two-way databinding [4];
  • The DataList has a number of properties that are required for the updating and deleting process, and these values are stored in view state. Therefore, when building a DataList that supports editing or deleting data, it is essential that the DataList's view state be enabled [4].

DataList Properties [3]:

The DataList, by default, lists its items in a single-column, multi-row table, which mimics the layout of a GridView with a single TemplateField. While this default layout is acceptable, we can maximize screen real estate by displaying multiple data source items per row. Accomplishing this is simply a matter of setting the:  
  • RepeatColumns property to the number of columns to display per row;
  • RepeatDirection property can be used to indicate whether the contents of the multi-column, multi-row table should be laid out horizontally from left to right, top to bottom or vertically from top to bottom, left to right; 
  • DataKeyField property [4] when updating or deleting, we need to be able to uniquely identify each item in the DataList. Set this property to the primary key field of the displayed data. Doing so will populate the DataList s DataKeys collection with the specified DataKeyField value for each DataList item.

DataList Templates [2]:

 When binding a data source to a FormView control through the FormView s smart tag, Visual Studio created an ItemTemplate, InsertItemTemplate, and EditItemTemplate. With the DataList, however, only an ItemTemplate is created. This is because the DataList does not have the same built-in editing and inserting support offered by the FormView. The DataList does contain edit- and delete-related events, and editing and deleting support can be added with a bit of code, but there s no simple out-of-the-box support as with the FormView.
In addition to the ItemTemplate, the DataList supports six other optional templates:
  • HeaderTemplate if provided, adds a header row to the output and is used to render this row;
  • AlternatingItemTemplate used to render alternating items;
  • SelectedItemTemplate used to render the selected item; the selected item is the item whose index corresponds to the DataList s SelectedIndex property;
  • EditItemTemplate used to render the item being edited;
  • SeparatorTemplate if provided, adds a separator between each item and is used to render this separator;
  • FooterTemplate - if provided, adds a footer row to the output and is used to render this row;
Example:
<asp:DataList ID="DataList1" runat="server" DataKeyField="ProductID" 
    DataSourceID="ObjectDataSource1">
    <SeparatorTemplate>        <hr />
    </SeparatorTemplate>
    <HeaderTemplate>
        <h3>Product Information</h3>
    </HeaderTemplate>
    <ItemTemplate>                       
        <h4><asp:Label ID="ProductNameLabel" runat="server" 
            Text='<%# Eval("ProductName") %>' /></h4>
        <table>
            <tr>
                <td class="ProductPropertyLabel">CategoryName:</td>
                <td><asp:Label ID="CategoryNameLabel" runat="server" 
                        Text='<%# Eval("CategoryName") %>' /></td>
                <td class="ProductPropertyLabel">SupplierName:</td>
                <td><asp:Label ID="SupplierNameLabel" runat="server" 
                    Text='<%# Eval("SupplierName") %>' /></td>
            </tr>
            <tr>
                <td class="ProductPropertyLabel">Qty/Unit:</td>
                <td><asp:Label ID="QuantityPerUnitLabel" runat="server" 
                        Text='<%# Eval("QuantityPerUnit") %>' /></td>  
                                    <td class="ProductPropertyLabel">Price:</td>
                <td><asp:Label ID="UnitPriceLabel" runat="server" 
                        Text='<%# Eval("UnitPrice") %>' /></td>                  
            </tr>
        </table>                   
    </ItemTemplate>
</asp:DataList>

DataList Events [2]:

When data is bound to a DataList, either from a data source control or through programmatically assigning data to the control s DataSource property and calling its DataBind() method, the DataList s DataBinding event fires, the data source enumerated, and each data record is bound to the DataList. For each record in the data source, the DataList creates a DataListItem object that is then bound to the current record. During this process, the DataList raises two events:
  • ItemCreated fires after the DataListItem has been created
  • ItemDataBound fires after the current record has been bound to the DataListItem
Example:
The following steps outline the data binding process for the DataList control.
  • The DataList s DataBinding event fires
  • The data is bound to the DataList
    For each record in the data source
       a. Create a DataListItem object
       b. Fire the ItemCreated event
       c. Bind the record to the DataListItem
       d. Fire the ItemDataBound event
       f. Add the DataListItem to the Items collection
  • ItemCommand [4] this event is raised when a Button, LinkButton, or ImageButton that has its  CommandName property set, is clicked from within a Repeater or DataList. For the DataList, if the CommandName property is set to a certain value, an additional event may be raised as well. This special CommandName property values include, among others:
        - "Cancel" raises the CancelCommand event;
        - "Edit" raises the EditCommand event;
        - "Update" raises the UpdateCommand event).
    Although this special events will be raised if the CommandName has this special values, the ItemCommand event will still be raised with them. So we can ignore this special events and treat everything inside the ItemCommand event if we prefer.(remember: these events are raised in addition to the ItemCommand event)
Example: 
aspx file:
<asp:DataList ID="ProductsDataList" runat="server"
    DataKeyField="ProductID"
    DataSourceID="ProductsObjectDataSource"
    RepeatColumns="2"
    OnItemCommand="ProductsDataList_ItemCommand">
    <ItemTemplate>
        <h5>
            <asp:Label ID="ProductNameLabel" runat="server"
                    Text='<%# Eval("ProductName") %>' />
        </h5>
        Price:
        <asp:Label ID="UnitPriceLabel" runat="server"
                 Text='<%# Eval("UnitPrice","{0:C}") %>' />
        <br />
        <asp:Button ID="EditButton" runat="server" 
                CommandName="Edit"
                Text="Edit" />
        <asp:Button ID="DeleteButton" runat="server"
                CommandName="Delete"
                Text="Delete"
                OnClientClick='return confirm("Eliminar?");' />
    </ItemTemplate>
    <EditItemTemplate>
        Product:<asp:TextBox ID="ProductNameTextBox" runat="server"
                             Text='<%# Eval("ProductName") %>' />
        <br />
        Price:<asp:TextBox ID="UnitPriceTextBox" runat="server"
                         Text='<%# Eval("UnitPrice", "{0:C}") %>' />
        <br />
        <asp:Button ID="UpdateButton" runat="server"
                CommandName="Update" Text="Update" />
        <asp:Button ID="CancelButton" runat="server"
                                   CommandName="Cancel" Text="Cancel" />
    </EditItemTemplate>
</asp:DataList>

cs file(s). We have two options here, use only the Datalist ItemCommand for every button clicked inside the Datalist, or since they have the special names set ("Edit", "Cancel", "Delete" and "Update") we can use the special events that each of them raises.
protected void ProductsDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    {
        ProductsDataList.EditItemIndex = e.Item.ItemIndex;
        ProductsDataList.DataBind();
    }
    
    else if (e.CommandName == "Cancel")
        returnToReadMode();                   
    
    else if (e.CommandName == "Update")
    {
        int productID = Convert.ToInt32(ProductsDataList.DataKeys[e.Item.ItemIndex]);

        TextBox nameTextBox = (TextBox)e.Item.FindControl("ProductNameTextBox");
        TextBox priceTextBox = (TextBox)e.Item.FindControl("UnitPriceTextBox");

        string productName = null;
        if (!String.IsNullOrEmpty(nameTextBox.Text.Trim()))
            productName = nameTextBox.Text.Trim();
        
        decimal? productPrice = null;
        if(!String.IsNullOrEmpty(priceTextBox.Text.Trim()))
            productPrice = decimal.Parse(priceTextBox.Text.Replace('.',',').Trim(),
                                    System.Globalization.NumberStyles.Currency);
        
        //ProductsBLL productsAPI = new ProductsBLL();
        ProductsAPI.UpdateProduct(productID, productName, productPrice);
        
        returnToReadMode();
    }

    else if (e.CommandName == "Delete")
    {
        int productID = (int)ProductsDataList.DataKeys[e.Item.ItemIndex];
        ProductsAPI.DeleteProduct(productID);

        returnToReadMode();
    }
}

protected void returnToReadMode()
{
    ProductsDataList.EditItemIndex = -1;
    ProductsDataList.DataBind();
}

or we could use the special events raised:
protected void ProductsDataList_CancelCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_UpdateCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_DeleteCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_EditCommand(object source, DataListCommandEventArgs e){}

to use them we would need to connect them to the Datalist:
<asp:DataList ID="ProductsDataList" runat="server"
    DataKeyField="ProductID"
    DataSourceID="ProductsObjectDataSource"
    RepeatColumns="2"
    OnItemCommand="ProductsDataList_ItemCommand" 
    OnCancelCommand="ProductsDataList_CancelCommand"
    OnEditCommand="ProductsDataList_EditCommand"
    OnUpdateCommand="ProductsDataList_UpdateCommand"
    OnDeleteCommand="ProductsDataList_DeleteCommand"> 

Related articles:
[1] - DataList Class (.NET Class Library)
[2] - Displaying Data with the DataList and Repeater Controls
[3] - Showing Multiple Records per Row with the DataList Control
[4] - An Overview of Editing and Deleting Data in the DataList

See this article for an example of RadioButtonList with databinding [1].

<asp:RadioButtonList ID="DiscontinuedChoice" runat="server"    
    SelectedValue='<%# Bind("Discontinued") %>'>
    <asp:ListItem Text="Active" Value="False" />
    <asp:ListItem Text="Discontinued" Value="True" />
</asp:RadioButtonList> 

Related articles:
[1] - Customizing the Data Modification Interface (Step 4: Using RadioButtons for the Discontinued Status)

By default, the validation controls automatically emit client-side validation script; they also provide server-side validation on postback, storing the cumulative result in the Page.IsValid property.

ASP.NET provides five built-in validation controls that are designed to be used to validate the value of a single input control [1]:

For more information on these five controls, check out the Validation Controls section of the ASP.NET Quickstart Tutorials.

Some control notes:

RequiredFieldValidator important properties:

  • ControlToValidate: All validation controls work by validating the input of a single ASP.NET Web control. Therefore, we need to indicate that the (for ex.) RequiredFieldValidator should validate against some TextBox in the page;
  • ErrorMessage: for ex. "You must provide the product's name". This is used by the ValidationSummary control;
  • Text: for ex. "*". This is the text that is displayed by the validation control if the validation fails (if this property value is omitted, the ErrorMessage property value is also the text displayed by the validation control on invalid input.);
  • ValidationGroup: associate this validation control with a set of validation controls;

CompareValidator important properties notes:

  • ControlToValidate: All validation controls work by validating the input of a single ASP.NET Web control. Therefore, we need to indicate that the (for ex.) RequiredFieldValidator should validate against some TextBox in the page;
  • ErrorMessage: for ex. "You must provide the product's name". This is used by the ValidationSummary control;
  • Text: for ex. "*". This is the text that is displayed by the validation control if the validation fails (if this property value is omitted, the ErrorMessage property value is also the text displayed by the validation control on invalid input.)
  • Operator: for ex. "GreaterThanEqual";
  • ValueToCompare: for ex. "0";
  • Type: for ex. "Currency";
  • ValidationGroup: associate this validation control with a set of validation controls;

Example:
<InsertItemTemplate>
    <asp:TextBox ID="InsertUnitPrice" runat="server"
Text='<%# Bind("UnitPrice") %>'></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
        ControlToValidate="InsertUnitPrice" 
        ErrorMessage="O preço é de preenchimento obrigatorio."
        ValidationGroup="InsertValidationControls">*</asp:RequiredFieldValidator>
    <asp:CompareValidator ID="CompareValidator2" runat="server" 
        ControlToValidate="InsertUnitPrice" 
        ErrorMessage="O preoço deverá ser superior a 0€" Operator="GreaterThan" 
        ValueToCompare="0"
        ValidationGroup="InsertValidationControls">*</asp:CompareValidator>
</InsertItemTemplate> 


ValidationSummary control:

This control displays the ErrorMessages of those validation controls in the page that detected invalid data. This summary data can be displayed as text on the web page or through a modal, client-side messagebox.

Relevant properties:
  • ShowSummary: (true/false) if the summary should be rendered on the page;
  • ShowMessageBox: (true/false) if the summary should be displayed as a messagebox (modal client-side popup); In this case the location of the Validation control on the page doesn't really matter, since it will display as a messagebox.
  • ValidationGroup: associate this validation control with a set of validation controls;

Other Notes:

  • ValidationGroup notes: The Button and Button-related controls in ASP.NET also include a ValidationGroup property. A validation group's validators are checked for validity only when a postback is induced by a Button that has the same ValidationGroup property setting. For example, in order for a DetailsView's Insert button to trigger a "someGroup" validation group we need to set the CommandField's ValidationGroup property to"someGroup". 
  • All of the ASP.NET validation controls repeat their validation logic immediately upon postback (on the server) and report the overall validity of the page inputs via the Page.IsValid property.
    If a user has JavaScript disabled  the client-side validation will be bypassed and a postback will ensue either the input data is valid or not. To prevent this situations we can check the validation on the server and if there are errors the server will respond with a new page with the Validation Controls rendered. To perform this we only need to check if the Page.IsValid property is true before executing the server code request.
    Some Controls already perform this check on server for us, like the GridView. [2]
    Example:


     protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            if (!Page.IsValid)
                return;
           (proceed execution only if the inputs are valid)
        }

Related articles:
[1] - Adding Validation Controls to the Editing and Inserting Interfaces
[2] - Adding Validation Controls to the DataList's Editing Interface

  • Add a hyperlink (that uses the querystring for args) to each row [1]:
Include a link titled "View Products" in each GridView row that, when clicked, takes the user to ProductsForSupplierDetails.aspx passing in the selected row's SupplierID value through the querystring.

For example, if user clicks on the View Products link for the Tokyo Traders supplier (which has a SupplierID value of 4), they should be sent to ProductsForSupplierDetails.aspx?SupplierID=4.

To accomplish this, add a HyperLinkField to the GridView, which adds a hyperlink to each GridView row. Start by clicking the Edit Columns link from the GridView's smart tag. Next, select the HyperLinkField from the list in the upper left and click Add to include the HyperLinkField in the GridView's field list.
 The HyperLinkField can be configured to use the same text or URL values the link in each GridView row, or can base these values on the data values bound to each particular row. To specify a static value across all rows use the HyperLinkField's Text or NavigateUrl properties. Since we want the link text to be the same for all rows, set the HyperLinkField's Text property to View Products.
 To set the text or URL values to be based on the underlying data bound to the GridView row, specify the data fields the text or URL values should be pulled from in the DataTextField or DataNavigateUrlFields properties. DataTextField can only be set to a single data field; DataNavigateUrlFields, however, can be set to a comma-delimited list of data fields.

We frequently need to base the text or URL on a combination of the current row's data field value and some static markup. In this tutorial, for example, we want the URL of the HyperLinkField's links to be ProductsForSupplierDetails.aspx?SupplierID=supplierID, where supplierID is each GridView's row's SupplierID value.

Notice that we need both static and data-driven values here: the ProductsForSupplierDetails.aspx?SupplierID= portion of the link's URL is static, whereas the supplierID portion is data-driven as its value is each row's own SupplierID value.

To indicate a combination of static and data-driven values, use the DataTextFormatString and DataNavigateUrlFormatString properties. In these properties enter the static markup as needed and then use the marker {0} where you want the value of the field specified in the DataTextField or DataNavigateUrlFields properties to appear. If the DataNavigateUrlFields property has multiple fields specified use {0} where you want the first field value inserted, {1} for the second field value, and so on.

Applying this to our tutorial, we need to set the DataNavigateUrlFields property to SupplierID, since that's the data field whose value we need to customize on a per-row basis, and the DataNavigateUrlFormatString property to ProductsForSupplierDetails.aspx?SupplierID={0}.

  •  The EmptyDataText property [1]:
If the user clicks on the View Products link for a supplier that doesn't have any products, the ProductsBySupplierDataSource ObjectDataSource in ProductsForSupplierDetails.aspx won't return any results. The GridView bound to the ObjectDataSource won't render any markup resulting in a blank region on the page in the user's browser. To more clearly communicate to the user that there are no products associated with the selected supplier we can set the GridView's EmptyDataText property to the message we want displayed when such a situation arises. I've set this property to "There are no products provided by this supplier":

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
   DataKeyNames="ProductID" DataSourceID="ObjectDataSource1"
   EmptyDataText ="Não existem produtos deste fornecedor."> 

  • Creating a Selectable GridView [2]
Simply check the Enable Selection checkbox in the GridView's smart tag, which will add a Select button to each row.

This adds a CommandField to the ProductsGrid GridView with its ShowSelectButton property set to True. This results in a Select button for each row of the GridView. By default, the Select buttons are rendered as LinkButtons, but you can use Buttons or ImageButtons instead through the CommandField's ButtonType property.

<asp:GridView ID="ProductsGrid" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="ProductID" DataSourceID="ObjectDataSource1">
    <Columns>
        <asp:CommandField ShowSelectButton="True"
                 ButtonType="Link" SelectText="Selecionar" />
        <asp:BoundField DataField="ProductName" HeaderText="ProductName" 
            SortExpression="ProductName" />
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" 
            SortExpression="UnitPrice" />
    </Columns>    
</asp:GridView>

When a GridView row's Select button is clicked a postback ensues and the GridView's SelectedRow property is updated. In addition to the SelectedRow property, the GridView provides the:
 The DataKeyNames property is used to associate one or more data field values with each row and is commonly used to attribute uniquely identifying information from the underlying data with each GridView row: 
  • SelectedValue property: returns the value of the first DataKeyNames data field for the selected row;
  • SelectedDataKey property returns the selected row's DataKey object, which contains all of the values for the specified data key fields for that row.
The DataKeyNames property is automatically set to the uniquely-identifying data field(s) when you bind a data source to a GridView, DetailsView, or FormView through the Designer. While this property has been set for us automatically, for the selectable GridView to work properly the DataKeyNames property must be set properly. (In this example we must ensure that the DataKeyNames property is set to "ProductID").

  • Disabling the Edit Button in each row based on the row data [3]:
The picture below shows a GridView where each "Discontinued" product has its "Edit" button disabled:
This can be achieved with the following code logic in the GridViews RowDataBound event (note: for this example the CommandField for the Edit Button was converted to a TemplateField where a Edit LinkButton has the id "EditButton". This way we can use the e.Row.FindControl("EditButton") to get a reference to it):

protected void ProductsBySupplier_RowDataBound(object sender, GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Get a reference to the product row
        Northwind.ProductsRow product = (Northwind.ProductsRow
                               ((System.Data.DataRowView)e.Row.DataItem).Row;

        //if the product is discontinued disable the edit button
        if (product.Discontinued)
        {               
            LinkButton editButton = (LinkButton)e.Row.FindControl("EditButton");
            editButton.Visible = false;
        }
    }        
} 

If we want to use the CommandField instead of converting it into a TemplateField then the reference to the Edit button can be achieved with:
 LinkButton editButton = (LinkButton)e.Row.Cells[0].Controls[0];

GridView Paging notes:

"Default Paging" Vs "Custom Paging" [5]:

  • Default Paging can be implemented by simply checking the Enable Paging option in the data Web control s smart tag; however, whenever viewing a page of data, the ObjectDataSource retrieves all of the records, even though only a subset of them are displayed in the page
  • Custom Paging improves the performance of default paging by retrieving only those records from the database that need to be displayed for the particular page of data requested by the user; however, custom paging involves a bit more effort to implement than default paging

Paging properties and methods [4]:

AllowPaging: Gets or sets a value indicating whether the paging feature is enabled;
PageSize: Gets or sets the number of records to display on a page in a GridView control;
PageIndex: indicates the current page being viewed (is indexed starting at 0, in the first page of data it will equal 0);
PageCount: indicates the total number of pages (starts counting at 1);
PagerStyle: indicates the style information for the paging interface (can specify settings like BackColor, ForeColor, CssClass, HorizontalAlign, and so on);
PagerSettings: contains a bevy of properties that can customize the functionality of the paging interface. Some examples are:
  • PagerSettings-PageButtonCount: indicates the maximum number of numeric page numbers displayed in the paging interface (the default is 10);
  • PagerSettings-Mode: indicates how the paging interface operates (can be set to:NextPrevious; NextPreviousFirstLast; Numeric; NumericFirstLast);

Custom Paging properties and methods [5]:

ASP.NET has already a built in mechanism to implement custom paging. To use it we must configure a set of properties of the web control (ex. GridView) associated DataSource:
  • SelectMethod: the BLL method to invoke to obtain the table data (ex. SelectMethod="GetProductsPaged"). This property is set when using the DataSource Configuration Wizard.
    Example of the Get
  • EnablePaging: must be set to true, indicating to the ObjectDataSource that it must pass to the SelectMethod two additional parameters, one to specify the Start Row Index (StartRowIndexParameterName), and one to specify the Maximum Rows (MaximumRowsParameterName);
  • StartRowIndexParameterName: the name of the first input parameter passed into the SelectMethod for custom paging purposes (ex. StartRowIndexParameterName="startRowIndex");
  • MaximumRowsParameterName: the name of the second input parameter passed into the SelectMethod for custom paging purposes (ex. MaximumRowsParameterName="maximumRows");
  • SelectCountMethod: the BLL method to invoke that returns the total number of records being paged through (ex. SelectCountMethod="TotalNumberOfProducts"); 
  • SortExpression: optional, in case we want to use sort with the custom paging. This property informs the ObjectDataSource to pass in the SortExpression parameter to the BLL method, based on the column that the user has requested to sort the results by. This property should be set to the same name of the parameter on the BLL method [6];
Note: if you used the DataSource Configuration Wizard it automaticly added  two <asp:Parameter> elements for the GetProductsPaged method s input parameters. By setting EnablePaging to true, these parameters will be passed automatically. So, remove the startRowIndex and maximumRows <asp:Parameter> Elements from the ObjectDataSource s Declarative Markup.


Paging Events [4]:

When a user sorts or pages through data, a workflow unfolds:
  1. A postback ensues
  2. The data Web control s pre-level event fires (PageIndexChanging or Sorting)
  3. All of the data is re-retrieved by the ObjectDataSource
  4. The data Web control s post-level event fires (PageIndexChanged or Sorted)

GridView Sorting Notes

Unable sort link on some GridViews Headers[4]:

When sorting is enabled on a GridView, each GridView field automatically has its SortExpression property assigned to the name of the data field in the ProductsRow class. For example, the ProductName BoundField's SortExpression is set to "ProductName", as shown in the following declarative markup:
<asp:BoundField DataField="ProductName" HeaderText="Product" 
     SortExpression="ProductName" />
A field can be configured so that it s not sortable by clearing out its SortExpression property (assigning it to an empty string):
<asp:BoundField DataField="ProductName" HeaderText="Product
     SortExpression="" />

Examining the Sorting Event Workflow [4]:

The following list details the sequence of steps that transpires when an end user sorts the data in a GridView:
  1. The GridView s Sorting event fires
  2. The GridView s SortExpression property is set to the SortExpression of the field whose sorting header LinkButton was clicked
  3. The ObjectDataSource re-retrieves all of the data from the BLL and then sorts the data using the GridView s SortExpression
  4. The GridView s PageIndex property is reset to 0, meaning that when sorting the user is returned to the first page of data (assuming paging support has been implemented)
  5. The GridView s Sorted event fires
Like with default paging, the default sorting option re-retrieves all of the records from the BLL. When using sorting without paging or when using sorting with default paging, there s no way to circumvent this performance hit (short of caching the database data). However,  it s possible to efficiently sort data when using custom paging.


GridView Render Control hierarchy [7]:

The process of data binding builds up the GridView s control hierarchy, which in reality is simply a Table instance composed of a collection of rows, each of which is composed of a collection of cells.

Specifically, the GridView s control collection contains:
  • a Table object at its root;
  • this Table contains multiple GridViewRow (which is derived from the TableRow class) for each record in the DataSource bound to the GridView;
  • and a TableCell object in each GridViewRow instance for each data field in the DataSource.
This table can be obtained with:
// Reference the Table the GridView has been rendered into 
Table table = (Table)SomeGridView.Controls[0];



Other Notes:
As discussed in this [article] it is vitally important that the GridView s view state be enabled (the default behavior) whenInserting, Updating or Deleting Data. If you set the GridView s EnableViewState property to false, you run the risk of having concurrent users unintentionally deleting or editing records. See WARNING: Concurrency Issue with ASP.NET 2.0 GridViews/DetailsView/FormViews that Support Editing and/or Deleting and Whose View State is Disabled for more information.

Related articles:
[1] - Master/Detail Filtering Across Two Pages
[2] - Master/Detail Using a Selectable Master GridView with a Details DetailView
[3] - Limiting Data Modification Functionality Based on the User
[4] - Paging and Sorting Report Data (see Step 5) 
[5] - Efficiently Paging Through Large Amounts of Data
[6] - Sorting Custom Paged Data
[7] - Creating a Customized Sorting User Interface

Notes:

Adding a "-- Choose a Category --" List Item [1]

When first displaying the DropDownList we may want to have a DropDownList item selected that says something like, "-- Choose a Category --".
To add a new list item to the DropDownList, go to its smart tag and select "Edit Items...". Add a new list item with the Text "-- Choose a Category --" and the Value -1.

Alternatively, you can add the list item by adding the following markup to the DropDownList:
<asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="ObjectDataSource1" DataTextField="CategoryName" 
    DataValueField="CategoryID" AutoPostBack="true"
    AppendDataBoundItems="True">
    <asp:ListItem Selected="True" Value="-1">-- Choose a category --</asp:ListItem>
</asp:DropDownList>

Additionally, we need to set the DropDownList control's AppendDataBoundItems to True because when the categories are bound to the DropDownList from the ObjectDataSource they'll overwrite any manually-added list items if AppendDataBoundItems isn't True.

Handling NULL Values:

Scenario [2]: We have a DropDownList bound to some DB data. The DropDownList value is assigned to "CategoryID" and its text to "CategoryName". The DB CategoryID can be assigned to a NULL value, yet the DropDownLists in the EditItemTemplates don't include a list item to represent a NULL value. This has two consequences:
  • User cannot use the DropDownList to change a product's category or supplier from a non-NULL value to a NULL one;
  • If a product has a NULL CategoryID, in the DB, this will result in an exception on the DropDownList. This is because the NULL value returned by CategoryID in the Bind() statement does not map to a value in the DropDownList (the DropDownList throws an exception when its SelectedValuenot in its collection of list items property is set to a value ).
In order to support NULL CategoryID values, we need to add a ListItem to the DropDownList to represent the NULL value. So, we set the AppendDataBoundItems property to true and manually add the additional ListItem. The databinding logic in ASP.NET will automatically convert a blank string to a NULL value and vice-a-versa. Therefore, we want the ListItem's Value to be an empty string:
<asp:DropDownList ID="Categories" runat="server"
    AppendDataBoundItems="true"
    DataSourceID="CategoriesDataSource" 
    DataTextField="CategoryName" 
    DataValueField="CategoryID" 
    SelectedValue='<%# Bind("CategoryID") %>'>
    <asp:ListItem Text="None" Value="" />
</asp:DropDownList>

Populating a DropDownList in code behind example [3]:

DropDownList1.Items.Clear();
ListItem item;
for (int i = 0; i < ProductsGridView.PageCount; i++)
{
    item = new ListItem("Page " + (i+1), i.ToString());
    DropDownList1.Items.Add(item);
}
DropDownList1.SelectedIndex = ProductsGridView.PageIndex; 

Related articles:
[1] - Master/Detail Filtering With a DropDownList
[2] - Customizing the Data Modification Interface (see Handling NULL Values section)
[3] - Paging and Sorting Report Data (Step4: Customizing the Paging Experience)

The DetailsView is pretty rigid in how it displays each record returned from the ObjectDataSource. We may want a more flexible view of the data.  

For example, rather than showing the product's name, category, supplier, price, and discontinued information each on a separate row, we may want to show the product name and price in an <h4> heading, with the category and supplier information appearing below the name and price in a smaller font size. And we may not care to show the property names (Product, Category, and so on) next to the values.

The FormView control provides this level of customization. Rather than using fields (like the GridView and DetailsView do), the FormView uses templates, which allow for a mix of Web controls, static HTML, and databinding syntax. If you are familiar with the Repeater control from ASP.NET 1.x, you can think of the FormView as the Repeater for showing a single record.

You can bind the FormView directly to a data source control through the FormView's smart tag, which will create a default ItemTemplate automatically (along with an EditItemTemplate and InsertItemTemplate, if the ObjectDatatSource control's InsertMethod and UpdateMethod properties are set). However, for this example let's bind the data to the FormView and specify its ItemTemplate manually. Start by setting the FormView's DataSourceID property to the ID of the ObjectDataSource control, ObjectDataSource1. Next, create the ItemTemplate so that it displays the product's name and price in an <h4> element and the category and shipper names beneath that in a smaller font size.

<asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource1" 
    AllowPaging="True" EnableViewState="false">
    <ItemTemplate>
        <h4><%#Eval("productName") %> (<%#Eval("unitPrice")%>)</h4>
        Category: <%#Eval("CategoryName")%>;
        Suplier: <%#Eval("SupplierName")%>
    </ItemTemplate>
</asp:FormView>

Like the DetailsView, the FormView only shows the first record returned from the ObjectDataSource. You can enable paging in the FormView to allow visitors to step through the products one at a time.

Related articles:
[1] - Displaying Data With the ObjectDataSource (A More Flexible Layout for Showing One Record at a Time)

Displaying Data With the ObjectDataSource [1]:
In previous tutorials we've seen how to programmatically bind data from the DAL and BLL to a data Web control in an ASP.NET page. This syntax assigning the data Web control's DataSource property to the data to display and then calling the control's DataBind() method was the pattern used in ASP.NET 1.x applications, and can continue to be used in your 2.0 applications.

However, ASP.NET 2.0's new data source controls offer a declarative way to work with data. Using these controls you can bind data retrieved from the BLL without having to write a line of code!

ASP.NET 2.0 ships with five built-in data source controls:

  • SqlDataSource: with this dara source control it is possible to access, insert, update, and delete database data directly from an ASP.NET page, bypassing the architecture. Doing so places the specific database queries and business logic directly in the web page. For sufficiently large or complex applications, designing, implementing, and using a tiered architecture is vitally important for the success, updatability, and maintainability of the application. Developing a robust architecture, however, may be unnecessary when creating exceedingly simple, one-off applications. The SqlDataSource can be used to access and modify data directly from a relational database, including Microsoft SQL Server, Microsoft Access, Oracle, MySQL, and others. NOTE: Contrary to the ObjectDataSource, the SqlDataSource control, lacks the properties for implementing custom paging. [4]
  • AccessDataSource: The sole difference between the AccessDataSource and SqlDataSource controls is how the database connection information is specified. The AccessDataSource control needs just the file path to the Access database file. The SqlDataSource, on the other hand, requires a complete connection string [4];
  • ObjectDataSource: with this data source control it is possible to declaratively interface with the architecture from the presentation layer;
  • XmlDataSource;
  • SiteMapDataSource;
although you can build your own custom data source controls, if needed. Since we have developed an architecture for our tutorial application, we'll be using the ObjectDataSource against our BLL classes.

Note:
Conceptually, both the ObjectDataSource and SqlDataSource controls are simply proxies to data. [4]
The ObjectDataSource's Configure Data Source wizard offers a quick way to specify the object it uses and to associate what methods of the object are invoked. You can, however, configure the ObjectDataSource through its properties, either through the Properties window or directly in the declarative markup. Simply set the TypeName property to the type of the underlying object to be used, and the SelectMethod to the method to invoke when retrieving data.
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
     SelectMethod="GetProducts" TypeName="ProductsBLL"> 
</asp:ObjectDataSource>
Even if you prefer the Configure Data Source wizard there may be times when you need to manually configure the ObjectDataSource, as the wizard only lists developer-created classes. If you want to bind the ObjectDataSource to a class in the .NET Framework such as the Membership class, to access user account information, or the Directory class to work with file system information you'll need to manually set the ObjectDataSource's properties.

The ObjectDataSource serves as a proxy for working with some other object. To configure the ObjectDataSource we specify this underlying object and how its methods map to the ObjectDataSource's Select, Insert, Update, and Delete methods. Once this underlying object has been specified and its methods mapped to the ObjectDataSource's, we can then bind the ObjectDataSource to a data Web control (like: GridView, DetailsView, RadioButtonList, and DropDownList).


To specify the ObjectDataSource's underlying object and how that object's methods map to the ObjectDataSource's, click on the Configure Data Source link from the ObjectDataSource's smart tag.

Passing input parameters [2]:
The ObjectDataSource can be used to invoke methods that expect input parameters, but in order to do so we must specify where the values for these parameters come from. The parameter values can be hard-coded or can come from a variety of dynamic sources, including: querystring values, Session variables, the property value of a Web control on the page, or others.


Programmatically Setting the ObjectDataSource's Parameter Values [3]:
Whenever the ObjectDataSource's Select method is invoked the ObjectDataSource first raises its Selecting event. The ObjectDataSource's underlying object's method is then invoked. Once that completes the ObjectDataSource's Selected event fires (Figure 1 illustrates this sequence of events). The parameter values passed into the ObjectDataSource's underlying object's method can be set or customized in an event handler for the Selecting event.

The final screen of the DataSource configuration wizard  asks us to provide the month parameter value's source. Since we'll set this value programmatically, leave the Parameter source set to the default None option and click Finish.

This will create a Parameter object in the ObjectDataSource's SelectParameters collection that does not have a value specified.


<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    OldValuesParameterFormatString="original_{0}" 
    onselecting="ObjectDataSource1_Selecting" 
    SelectMethod="GetEmployeesByHiredDateMonth" TypeName="EmployeesBLL">
    <SelectParameters>
        <asp:Parameter Name="month" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>

To set this value programmatically, we need to create an event handler for the ObjectDataSource's Selecting event.

protected void ObjectDataSource1_Selecting(object sender,
ObjectDataSourceSelectingEventArgs e)
{
    e.InputParameters["month"] = DateTime.Now.Month;
}

We can also assign a value directly to a ObjectDataSource parameter.
For example if we want to set the "CategoryID" parameter of the next ObjectDataSource with a value passed by querystring we could do it in code behind with:
aspx file:
<asp:ObjectDataSource ID="CategoryProductsDataSource" runat="server" 
    OldValuesParameterFormatString="original_{0}" 
    SelectMethod="GetProductsByCategoryID" TypeName="ProductsBLL">
    <SelectParameters>
        <asp:Parameter Name="categoryID" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource> 

cs file:
CategoryProductsDataSource.SelectParameters["categoryID"].DefaultValue =
                                Page.Request.QueryString["id"];


Related articles:
[1] - Displaying Data With the ObjectDataSource
[2] - Declarative Parameters
[3] - Programmatically Setting the ObjectDataSource's Parameter Values
[4] - Querying Data with the SqlDataSource Control

<div id="navigation">
    <ul>
        <li>
            <asp:HyperLink runat="server" ID="lnkHome" 
             NavigateUrl="~/Default.aspx" Text="Home" />
        </li>
        <asp:Repeater ID="menu" runat="server" DataSourceID="SiteMapDataSource1">
            <ItemTemplate>
                <li>
                    <asp:HyperLink runat="server" 
                     NavigateUrl='<%#Eval("url") %>' Text='<%# Eval("title") %>' />
                    <asp:Repeater runat="server" 
                     DataSource='<%# ((SiteMapNode) Container.DataItem).ChildNodes %>'>
                        <HeaderTemplate>
                            <ul>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <li>
                                <asp:HyperLink ID="HyperLink1" runat="server" 
                                 NavigateUrl='<%#Eval("url") %>' Text='
                                 <%# Eval("title") %>' />
                            </li>
                        </ItemTemplate>
                        <FooterTemplate>
                            </ul>
                        </FooterTemplate>
                    </asp:Repeater>
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ul>
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" 
     ShowStartingNode="false" />
</div> 

Note:
The __VIEWSTATE form field generated by the master page adds roughly 1,800 bytes to the page's generated markup. This extra bloat is due primarily to the Repeater control, as the contents of the SiteMapDataSource control are persisted to view state. While an extra 1,800 bytes may not seem like much to get excited about, when using a GridView with many fields and records, the view state can easily swell by a factor of 10 or more.
View state can be disabled at the page or control level by setting the EnableViewState property to false, thereby reducing the size of the rendered markup.
Related articles:
[1] - Master Pages and Site Navigation

In a nutshell, the ListView control provides a very flexible means for displaying a collection of data while still offerring rich data features like paging, sorting, editing, inserting, and deleting.
 
Usage example: let's add a ListView control to the left column in the Lessons section that renders an unordered list with a list item for each node defined in the site map [1].

Notes:

<asp:ListView ID="LessonsList" runat="server" DataSourceID="LessonsDataSource">
    <LayoutTemplate>
        <ul>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
        </ul>
    </LayoutTemplate>
    <ItemTemplate>
        <li>
            <asp:HyperLink runat="server" ID="lnkLesson"
               NavigateUrl='<%# Eval("Url") %>'  Text='<%# Eval("Title") %>' />
        </li>
    </ItemTemplate>
</asp:ListView> 
The LayoutTemplate generates the markup for an unordered list (<ul>...</ul>) while the ItemTemplate renders each item returned by the SiteMapDataSource as a list item (<li>) that contains a link to the particular lesson [1].
Note: To output a particular field value in the ItemTemplate, use the databinding syntax, <%# Eval("columnName") %> [2].

We can also explicitly add a bullet item for Home in the LayoutTemplate [1]:
<LayoutTemplate>
    <ul>
        <li>
            <asp:HyperLink runat="server" ID="lnkLesson"
               NavigateUrl="~/Default.aspx" Text="Home" />
        </li>
        <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
    </ul>
</LayoutTemplate>  


Another usage example [3]:
<asp:ListView ID="ListView1" runat="server" DataSourceID="LessonsDataSource">
    <LayoutTemplate>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
    </LayoutTemplate>
    <ItemTemplate>
            <asp:HyperLink runat="server" ID="lnkLesson"
               NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Title") %>' />
    </ItemTemplate>
    <ItemSeparatorTemplate>
            |
     </ItemSeparatorTemplate>
</asp:ListView> 

Related articles:
[1] - Specifying the Title, Meta Tags, and Other HTML Headers in the Master Page
[2] - Using ASP.NET 3.5's ListView
[3] - Specifying the Master Page Programmatically (see Step3)

The ListBox is a very handy control that allows your visitors to select from a list of items, with the option to select multiple items from the list. The DropDownList() control is limited to a single selection, so if you want the flexibility of allowing the possibility of multiple selections, the ListBox control is just want you need.[1]


Related articles:

[1] - ListBox Control Overview: Artigo sucinto exemplificando várias formas de interagir com o controlo ListBox.

The SiteMapPath (aka breadcrumb or eyebrow) Displays a navigation path that shows the user the current page location and displays links as a path back to the home page.

Note: You can help automate the process of updating the site map file when adding new ASP.NET pages using K. Scott Allen's free Visual Studio Site Map Macro.

Related articles:
[1] - Specifying the Title, Meta Tags, and Other HTML Headers in the Master Page (see Step3);
[2] -  Examining ASP.NET 2.0's Site Navigation;

The DetailsView is pretty rigid in how it displays each record returned from the ObjectDataSource. If you want a more flexible view of the data see the  FormView control that provides a higher level of customization.

Notes:
Algumas propriedades úteis:

    <asp:DetailsView ID="NewProduct" runat="server" Height="50px" Width="125px" 
        AutoGenerateRows="False" DataSourceID="NewProductDataSource" 
       DefaultMode="Insert"AllowPaging="True">
        <Fields>
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" 
                SortExpression="ProductName" />
            <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" 
                SortExpression="UnitPrice" />
            <asp:CommandField ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>

As propriedades AllowPaging e ShowInsertButton podem ser definidas através da smart tag do controlo. Já a propriedade DefaultMode pode ser definida no código/PropertiesPanel e permite as opções "Insert", "Edit" e "ReadOnly", definindo a forma como o controlo é exibido.

Referências:

Image Control Notes:
O controlo Image disponibiliza um conjunto de operações que não são possiveis com a tag "img" normal de HTML. Um exemplo é possibilidade de utilizar endereços relativos de forma bastante flexivel  em vez de endereços absolutos (while hard coding in the absolute URL works, it tightly couples your HTML to the website's server and folder location, which may change):

Keep in mind that only ASP.NET server controls transform the ~ in their URL-related properties. If a ~ appears in static HTML markup, such as <img src="~/Images/PoweredByASPNET.gif" />, the ASP.NET engine sends the ~ to the browser along with the rest of the HTML content. The browser assumes that the ~ is part of the URL. For example, if the browser receives the markup <img src="~/Images/PoweredByASPNET.gif" /> it assumes there is a subfolder named ~ with a subfolder Images that contains the image file PoweredByASPNET.gif.
To fix the image markup in Site.master, replace the existing <img> element with an ASP.NET Image Web control. (article)

Problema:

ASP.NET Image control automaticly renders images with no border: an inline style attribute with "border-width to 0px" is set on the rendered images. This brings issues with CSS control over this images.
It's silly but whoever in Microsoft wrote the render method of that control decided to put a style="border-width:0px;" as a default. 

Soluções:
Use the "runat=server" method on a normal html image:<img runat=server src=~/somefile.gif> o "~" será transformado automaticamente na pasta root (tal como no controlo Image);
Ou criar uma nova class que modifique este comportamento do controlo Image: tal como demostrado neste artigo.