This is a migrated thread and some comments may be shown as answers.

Selecting selected item in RadGrid

6 Answers 773 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Martin
Top achievements
Rank 1
Martin asked on 31 May 2011, 07:26 AM
Hello,

I have a dynamically generated page and a RadGrid on it.

The Grid is defined as follows:
           protected virtual void SetGrid(CustomFormPageHandler form, ASPXListFrameDefinition definition)
        {
            selectedID = ((FrameObjects.GetFrameControlId(FrameName) != Definition.ID) ? -9 : FrameObjects.GetFrameObjectID(FrameName));
  
            //Grid.DataSource = OWData;
            //if (!IsLOV)
            Grid.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
  
            Grid.DataBinding += new EventHandler(GridDataBinding);
  
            Grid.DataBound += new EventHandler(Grid_DataBound);
  
            Grid.ItemDataBound += new GridItemEventHandler(GridItemDataBoundEvent);
            Grid.ColumnCreated += new GridColumnCreatedEventHandler(Grid_ColumnCreated);
  
            Grid.DataSourceID = OWData.ClientID;
            Grid.ID = definition.ID;
            Grid.AllowPaging = true;
            Grid.AllowSorting = true;
  
            Grid.AllowFilteringByColumn = !definition.HideFilterRow;
  
            if (!IsLOV)
            {
                Grid.Height = (Unit.Parse(definition.Height));
                Grid.Width = (Unit.Parse(definition.Width));
            }
            else
            {
                //   Grid.Height = new Unit("100%");// (Unit.Parse(definition.Height));
                Grid.Width = new Unit("100%"); //(Unit.Parse(definition.Width));
            }
  
            Grid.ClientSettings.EnableAlternatingItems = true;
            Grid.ClientSettings.Scrolling.AllowScroll = true;
  
            Grid.ClientSettings.EnablePostBackOnRowClick = true;
  
            Grid.ClientSettings.Resizing.AllowResizeToFit = true;
            Grid.ClientSettings.Selecting.AllowRowSelect = true;
  
            Grid.AutoGenerateColumns = false;
  
            Grid.MasterTableView.AllowMultiColumnSorting = true;
            Grid.MasterTableView.ShowHeadersWhenNoRecords = true;            
            Grid.MasterTableView.AlternatingItemStyle.BackColor = Color.LightGray;
            Grid.MasterTableView.DataKeyNames = new string[] { "ID" };
  
            if (definition.Attribute.Count() > 1)
            {
                Grid.GroupingEnabled = true;
                Grid.ShowGroupPanel = true;
                Grid.ClientSettings.AllowDragToGroup = true;
                Grid.ClientSettings.Resizing.AllowColumnResize = true;
                Grid.ClientSettings.Resizing.EnableRealTimeResize = true;
                Grid.ClientSettings.EnableRowHoverStyle = true;
            }
        }

When I select an element, a detail is redrawn, everything works fine.
When I click on the selected item again, the postback is called, but no events are fired.
The site draws RadGrid with blank rows, the number of rows corresponds to the original number, but they do not contain any text.
Detail, which is drawn from the events Grid_DataBound, is not rendered because the event is not called.

If I click on the another item, which is not selected, everythings work fine again.

Can someone help?

Best regards
Martin

6 Answers, 1 is accepted

Sort by
0
Vasil
Telerik team
answered on 31 May 2011, 03:50 PM
Hi Martin,

When you click on the selected item again, post-back will happen because EnablePostBackOnRowClick is set to true in your client settings of the grid.
However, clicking on the selected row does not deselects it, and in this case the row remain selected. Because of this SelectedIndexChanged should not be fired, thus there is not changing in the selected index(selection remains the same).

There are two ways to workaround this:

1) Use server side selection/deselection like in this online demo:
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/selectrowwithcheckbox/defaultcs.aspx
If you deselect a row using the link buttons, the SelectedIndexChanged will be properly fired.

2) Disable the automatic post-back on row click for the grid, and handle the OnRowClick event. Depending on the currently selected status of the clicked row you could manually fire deselectItem or selectItem commands.

All the best,
Vasil
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Martin
Top achievements
Rank 1
answered on 10 Jun 2011, 07:24 AM
Hello,

I found that the problem is caused by the dynamically created GridTemplateColumn. I create them in the same way as described here
http://www.telerik.com/help/aspnet/grid/grdprogrammaticcreation.html - Creating ItemTemplate/EditItemTemplate of GridTemplateColumn programmatically

When I select anything the row became selected, but no DataBind event is fired, so the text is lost.

This happen on the standart Grid with dynamically created temlate column as on dynamically created Grid with dynamic template column.

Is there some workaround or what am I doing wrong?

Here is example

default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TelerikTemplateColumn._Default" %>
  
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>
    <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1" 
        AllowFilteringByColumn="True" AllowPaging="True" AllowSorting="True" 
        CellSpacing="0" GridLines="None" ShowGroupPanel="True">
        <ClientSettings AllowDragToGroup="True" EnablePostBackOnRowClick="true" EnableAlternatingItems="true" EnableRowHoverStyle="true">
        <Resizing AllowColumnResize="true" EnableRealTimeResize="true"/>
            <Selecting AllowRowSelect="True" />
            <Scrolling AllowScroll="True" UseStaticHeaders="True" />
        </ClientSettings>
        <MasterTableView AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
            <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn DataField="nazev" FilterControlAltText="Filter nazev column"
                    HeaderText="nazev" SortExpression="nazev" UniqueName="nazev">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("nazev", "{0}") %>'></asp:Label>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="kod" FilterControlAltText="Filter kod column"
                    HeaderText="kod" SortExpression="kod" UniqueName="kod">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="jmeno" FilterControlAltText="Filter jmeno column"
                    HeaderText="jmeno" SortExpression="jmeno" UniqueName="jmeno">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="prijmeni" FilterControlAltText="Filter prijmeni column"
                    HeaderText="prijmeni" SortExpression="prijmeni" UniqueName="prijmeni">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="titul" FilterControlAltText="Filter titul column"
                    HeaderText="titul" SortExpression="titul" UniqueName="titul">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="titul_za_jmenem" FilterControlAltText="Filter titul_za_jmenem column"
                    HeaderText="titul_za_jmenem" SortExpression="titul_za_jmenem" UniqueName="titul_za_jmenem">
                </telerik:GridBoundColumn>
            </Columns>
            <EditFormSettings>
                <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                </EditColumn>
            </EditFormSettings>
        </MasterTableView>
        <FilterMenu EnableImageSprites="False">
        </FilterMenu>
        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
        </HeaderContextMenu>
    </telerik:RadGrid>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FamaPlusJadro_TestConnectionString %>"
        SelectCommand="SELECT [nazev], [kod], [jmeno], [prijmeni], [titul], [titul_za_jmenem] FROM [cosoba]">
    </asp:SqlDataSource>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.Web.UI.HtmlControls;
  
namespace TelerikTemplateColumn
{
    public partial class _Default : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            DefineGrid();
  
            base.OnInit(e);
        }
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridTemplateColumn templateColumn = new GridTemplateColumn();
                templateColumn.ItemTemplate = new ColumnTemplate();
                RadGrid1.MasterTableView.Columns.Add(templateColumn);
            }
        }
  
        protected void DefineGrid()
        {
            Telerik.Web.UI.RadGrid grid = new Telerik.Web.UI.RadGrid();
  
            grid.ID = "testGrid";
  
            Form.Controls.Add(grid);
  
            grid.ClientSettings.EnablePostBackOnRowClick = true;
            grid.ClientSettings.Selecting.AllowRowSelect = true;
  
            grid.AutoGenerateColumns = false;
  
            grid.DataSourceID = SqlDataSource1.ID;//OWData.ID;
  
            GridTemplateColumn templateColumn = new GridTemplateColumn();
            templateColumn.ItemTemplate = new ColumnTemplate();
  
            templateColumn.HeaderText = "Prijmeni";
  
            grid.MasterTableView.Columns.Add(templateColumn);
        }
    }
  
    #region ColumnTemplate
    /// <summary>
    /// Templatová třída pro buňku gridu
    /// </summary>
    public class ColumnTemplate : ITemplate
    {
        #region Fields (3)
  
        private string colName;
        private string displayFormat;
        //private ASPXListFrame parent;
  
        #endregion Fields
  
        #region Constructors (1)
  
        /// <summary>
        /// Initializes a new instance of the <see cref="ColumnTemplate"/> class.
        /// </summary>
        /// <param name="cName">Name of the c.</param>
        /// <param name="displayFormat">The display format.</param>
        /// <param name="parent">The parent.</param>
        public ColumnTemplate()
        {   
        }
  
        #endregion Constructors
  
        #region Methods (2)
  
        // Public Methods (2) 
  
        /// <summary>
        /// When implemented by a class, defines the <see cref="T:System.Web.UI.Control"/> object that child controls and templates belong to. These child controls are in turn defined within an inline template.
        /// </summary>
        /// <param name="container">The <see cref="T:System.Web.UI.Control"/> object to contain the instances of controls from the inline template.</param>
        public void InstantiateIn(Control container)
        {
            HtmlGenericControl lControl = new HtmlGenericControl("div");
            lControl.ID = "lControl";
            lControl.DataBinding += new EventHandler(lControl_DataBinding);            
  
            container.Controls.Add(lControl);
        }
  
        /// <summary>
        /// Handles the DataBinding event of the lControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void lControl_DataBinding(object sender, EventArgs e)
        {
            HtmlGenericControl l = (HtmlGenericControl)sender;
            GridDataItem container = (GridDataItem)l.NamingContainer;            
  
            string text = ((DataRowView)container.DataItem).Row[1].ToString();
  
            l.Controls.Add(new LiteralControl(text));
        }
  
        #endregion Methods
    }
  
    #endregion ColumnTemplate
}


Thanks
Best regards
Martin
0
Vasil
Telerik team
answered on 15 Jun 2011, 09:12 AM
Hello Martin,

In your code you are creating a template column in Page_Init and another one in Page_Load.

Creating columns in the Page_Load event handler does not work for template columns. For the controls inside a template to persist their ViewState, the grid must be generated completely in the code-behind using the Page_Init event. That way, template controls are instantiated before the LoadViewState event of the page.

Note that you are referencing to the old help topic(this about the classic ASP.NET controls) in your last post. For programmatic creation of the RadGrid for ASP.NET AJAX, you should better read from here: http://www.telerik.com/help/aspnet-ajax/grid-programmatic-creation.html

I hope this helps.

Greetings,
Vasil
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Martin
Top achievements
Rank 1
answered on 23 Jun 2011, 09:17 AM
Hello,

there is no difference between creating the grid in page_load or page_int. The situation is always same. When I click on templatecolumn, all text from all template fields is lost.

Exactly when I use the example from the link which you refer and when I set the grid as
grid.ClientSettings.EnablePostBackOnRowClick = true;
grid.ClientSettings.Selecting.AllowRowSelect = true;

the text from all template fields is lost, 'cause databinding event on TemplateItem isn't called.

I need some workaround. I cannot use server side selection, because the customer ...

Thanks
Best regard
Martin Vybiral
0
Accepted
Vasil
Telerik team
answered on 27 Jun 2011, 04:06 PM
Hi Martin,

When you select a row or just make a post-back, the grid will not rebind. Instead, it will use the data saved in the ViewState.
So in case that you use controls with ViewState inside the GridTemplateColumn, the text will be saved and you will see it after the page reloads. If the controls does not have ViewState they will not be recreated properly and you will not see their value.

One solution will be to use Asp:Label instead of LiteralControl inside your templates for showing text. Another approach will be to turn off the view state of the grid, thus this will make it to rebind on every post-back.

Regards,
Vasil
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Martin
Top achievements
Rank 1
answered on 29 Jun 2011, 07:49 AM
Thank you very much, now its work.
Tags
Grid
Asked by
Martin
Top achievements
Rank 1
Answers by
Vasil
Telerik team
Martin
Top achievements
Rank 1
Share this question
or