Showing posts with label Command Column. Show all posts
Showing posts with label Command Column. Show all posts

Saturday, 30 May 2009

Move Command Link Column to End Column – Dynamic Data

Whilst answering this question Move Edit, Details, Delete (col 0) to the Rightmost column of table on the Dynamic Data Forum I found this had been answered before (Move GridView command column or dynamically append columns) and decided to post it to my blog in full for easy access.

The post suggest using IAutoFieldGenerator to add the command column to the end like this:

public ICollection GenerateFields(Control control)
{
    // Get all of table's columns, take only the ones that should be automatically included in a fields collection,
    // sort the result by the ColumnOrderAttribute, and for each column create a DynamicField
    var fields = from column in _table.Columns
                 where IncludeField(column)
                 orderby ColumnOrdering(column), column.Name
                 select new DynamicField()
                 {
                     DataField = column.Name,
                     HeaderText = column.DisplayName
                 };

    List<DynamicField> flds = fields.ToList();
    if (_table.PrimaryKeyColumns.Count > 0)
    {
        // get the first primary key field                
        DynamicField ctrl = new DynamicField();
        ctrl.HeaderText = "Commands";
        ctrl.DataField = _table.PrimaryKeyColumns[0].Name;
        ctrl.UIHint = "GridCommand";
        flds.Add(ctrl);
    }

    return flds;
}

Listing 1 – GenerateFields method of the IAutoFieldGenerator

The main change to my usual IAutoFieldGenerator is shown in Bold Italic this works by only adding the GridCommand FieldTemplate if the table a=has a Primary Key.

<asp:HyperLink 
    ID="EditHyperLink" 
    runat="server" 
    NavigateUrl='<%# Table.GetActionPath(PageAction.Edit, Row) %>' 
    Text="Edit" />
&nbsp;
<asp:LinkButton 
    ID="DeleteLinkButton" 
    runat="server" 
    CommandName="Delete" 
    CausesValidation="false" 
    Text="Delete" 
    OnClientClick='return confirm("Are you sure you want to delete this item?");' />
&nbsp;
<asp:HyperLink 
    ID="DetailsHyperLink" 
    runat="server" 
    NavigateUrl='<%# Table.GetActionPath(PageAction.Details, Row) %>' 
    Text="Details" />

Listing 2 – GridCommand FieldTemplate

In Listing 2 we see the GridCommand FieldTemplate layed out neatly (you may need to tidy it so that it is similar to the section it is copied form in the List page. >&nbsp;<)

Download

The download contains the full IAutoFieldGenerator and GridCommand FieldTemplate plus Column sort capability.