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

RadGrid added custom controls are lost during postback

4 Answers 304 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Stacy
Top achievements
Rank 1
Stacy asked on 24 Mar 2010, 06:15 PM
I'm currently working on a web site reporting system, using the RadGrid.  The system must be able to support multiple ReportTypes which return different number of columns, column names, and even hierarchy.  I've setup a system that is driven by xml files and there are virtually no hard coded values, column names, templates, and so forth.  It needs to be lightweight and dynamic. Most of the RadGrid settings are pulled in at the Page_Init event.  The application is dynamically buidling columns with AutoGenerateColumns=true.

Everything is working great to this point but, I've run into a problem which I hope some of you can help me with.  I dynamically create image icons and link to javascript at the column header level and also at the row level.  Works great until a user initiaites some event that raises a PostBack at the hierarchy's child level.  My custom controls added to the RadGrid are lost in the PostBack.   Obviously I am doing something wrong but, I'm not sure how to address this.

In the code below you'll see that I am creating controls and adding them to the RadGrid. gridDataItem[gridColumn.UniqueName].Controls.Add controls collection.  These are the controls which get lost in the PostBack.

<telerik:RadAjaxPanel ID="ParentRadAjaxPanel" runat="server">  
<telerik:RadGrid ID="ParentRadGrid" runat="server" EnableEmbeddedSkins="false" Skin="BIC3RadSkin" 
    OnItemDataBound="RadGrid_ItemDataBound" OnColumnCreated="RadGrid_ColumnCreated" 
    OnNeedDataSource="RadGrid_NeedDataSource" OnSortCommand="RadGrid_SortCommand">  
    <MasterTableView> 
    </MasterTableView> 
</telerik:RadGrid> 
</telerik:RadAjaxPanel> 


    protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs newGridDataItem)  
    {  
        try 
        {  
            RadGrid radGrid = (RadGrid)sender;
            #region Create Custom Header  
 
            if (newGridDataItem.Item.ItemType == GridItemType.Header)  
            {
                #region Create links to charts  
 
                    ...  
                    // Box a the ItemType as it is easier to use  
                    GridHeaderItem gridHeaderItem = (GridHeaderItem)newGridDataItem.Item;  
 
                    // Iterate thorugh every column and format the value  
                    foreach (GridColumn gridColumn in radGrid.MasterTableView.RenderColumns)  
                    {  
                        if (gridColumn.ColumnType != "GridExpandColumn" && gridColumn.ColumnType != "GridRowIndicatorColumn")  
                        {  
                            ...  
                            try 
                            {  
                                // Create a LinkButton control instead of setting the columns' .text property or the javascript will not work  
                                LinkButton linkButton = (LinkButton)gridHeaderItem[gridColumn.UniqueName].Controls[0];  
                                linkButton.Text = gridColumn.UniqueName;  
 
                                // Create a hyperLink control for the chart to work and does not interfere with the sort LinkButton  
                                if (_report.Grids[radGrid.ID][gridColumn.UniqueName].ChartColumnLink == true)  
                                {  
                                    String chartParameters = String.Format(" <a alt=\"Click to view chart\" href=\"javascript:ViewChart('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}');\"><img border=\"0\" src=\"images/iconChart.gif\"></a>", _report.ManagerUserID.ToString(), _report.DepartmentID, Convert.ToByte(_report.DepartmentDrillDown), _report.Location, Convert.ToByte(_report.ShiftWindow), _report.StartDate.ToShortDateString(), _report.EndDate.ToShortDateString(), _report.ReportType, _report.AggregationPeriod, gridColumn.UniqueName);  
 
                                    HyperLink chartHyperLink = new HyperLink();  
                                    chartHyperLink.Text = chartParameters;  
                                    gridHeaderItem[gridColumn.UniqueName].Controls.Add(chartHyperLink);  
                                }  
                            }  
                            catch 
                            {  
                                // If this fails, allow the column name to go w/o the chart link by default  
                            }  
                        }  
                    }  
                }
                #endregion Create links to charts  
            }
            #endregion Create Custom Header  
 
            ... // Create Custom Footer ommitted for easier troubleshooting  
 
            #region Put the proper formatting on values before display  
 
            if ((newGridDataItem.Item is GridDataItem) == true)  
            {  
                ...  
                GridDataItem gridDataItem = (GridDataItem)newGridDataItem.Item;  
 
                // Iterate thorugh every column and format the value  
                foreach (GridColumn gridColumn in radGrid.MasterTableView.RenderColumns)  
                {  
                    if (_report.Grids[radGrid.ID].ContainsKey(gridColumn.UniqueName) == true)  
                    {  
                        // Create the grid data item text in a control or .text property  
                        Label textLabel = new Label();  
                        if (gridDataItem[gridColumn.UniqueName].Text == "NaN")  
                        {  
                            // Weird: Add both text and a control. If there are more controls added below, the text is hidden but, if there are no other controls, the text will show.  
                            textLabel.Text = RadGrid_FormatText(radGrid, gridColumn.UniqueName, "0");  
                            gridDataItem[gridColumn.UniqueName].Text = RadGrid_FormatText(radGrid, gridColumn.UniqueName, "0");  
                        }  
                        else 
                        {  
                            // Do not display items that are special case exceptions governed by the .ReplaceHierarchyParentText property from xml  
                            if (String.IsNullOrEmpty(_report.Grids[radGrid.ID][gridColumn.UniqueName].ReplaceHierarchyParentText) == false && gridDataItem.OwnerTableView.ParentItem == null)  
                            {  
                                textLabel.Text = _report.Grids[radGrid.ID][gridColumn.UniqueName].ReplaceHierarchyParentText;  
                                gridDataItem[gridColumn.UniqueName].Text = _report.Grids[radGrid.ID][gridColumn.UniqueName].ReplaceHierarchyParentText;  
                            }  
                            else 
                            {  
                                // Weird: Add both text and a control. If there are more controls added below, the text is hidden but, if there are no other controls, the text will show.  
                                textLabel.Text = RadGrid_FormatText(radGrid, gridColumn.UniqueName, gridDataItem[gridColumn.UniqueName].Text);  
                                gridDataItem[gridColumn.UniqueName].Text = RadGrid_FormatText(radGrid, gridColumn.UniqueName, gridDataItem[gridColumn.UniqueName].Text);  
                            }  
                        }  
 
                        gridDataItem[gridColumn.UniqueName].Controls.Add(textLabel);
                        #region Create a hyperLink control for the chart to work and does not interfere with the sort  
 
                        // Create a hyperLink control for the chart to work and does not interfere with the sort LinkButton  
                        if (_report.Grids[radGrid.ID][gridColumn.UniqueName].ChartRowLink == true)  
                        {  
                            String chartParameters = String.Format(" <a alt=\"Click to view chart\" href=\"javascript:ViewChart('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}');\"><img border=\"0\" src=\"images/iconChart.gif\"></a>", gridDataItem[_childRadGridProperties["MasterTableView.DataKeyNames"]].Text, _report.DepartmentID, Convert.ToByte(_report.DepartmentDrillDown), _report.Location, Convert.ToByte(_report.ShiftWindow), _report.StartDate.ToShortDateString(), _report.EndDate.ToShortDateString(), _report.ReportType, _report.AggregationPeriod, gridColumn.UniqueName);  
 
                            HyperLink chartHyperLink = new HyperLink();  
                            chartHyperLink.Text = chartParameters;  
 
                            gridDataItem[gridColumn.UniqueName].Controls.Add(chartHyperLink);  
                        }
                        #endregion Create a hyperLink control for the chart to work and does not interfere with the sort  
                    }  
                }  
            }
            #endregion Put the proper formatting on values before display  
        }  
        catch (Exception exception)  
        {  
            //UNDONE: Wireup error handler object  
            Console.Write("error");  
        }  
    } 

Thanks!

Stacy

4 Answers, 1 is accepted

Sort by
0
Accepted
Shinu
Top achievements
Rank 2
answered on 25 Mar 2010, 06:32 AM
Hello,

A better approach to add a dynamically created control to GridItem is creating the controls in ItemCreated event handler. Also checkout the following documentation for more information.
Distinguishing the major differences between ItemCreated and ItemDataBound events

-Shinu.
0
Stacy
Top achievements
Rank 1
answered on 25 Mar 2010, 11:38 PM
Thank you Master Shinu, that was exactly what I was looking for.  That information with the adjustment of code from the server side code behind into a javascript call (referenced below) has rectified my issue.  Thanks for your help!

http://www.telerik.com/help/aspnet-ajax/grdgettingcellvaluesforselectedrowsclientside.html

:P
0
Robert Jakech
Top achievements
Rank 1
answered on 26 Mar 2010, 07:29 AM
Dear Shinu,

I am inserting/Editing records in a Radgrid through a usercontrol.

I need a label on the usercontrol so that when i click save, i have  a message displayed on the Label saying 'RECORDS SUCCESSFULLY SAVED'
However, my message seem not  to appear.

Check the attached screen shot and please kindly help me with a code that can achieve that.

thanks

0
Stacy
Top achievements
Rank 1
answered on 26 Mar 2010, 07:39 AM
EEEK, earlier while reading these articles made sense.  However, I'm more confused now  than in the beginning.  According to the article found on http://www.telerik.com/help/aspnet-ajax/grddistinguishdifferencesbetweenitemcreateditemdatabound.html, I have the following questions:

*** begin excerpt ***
Q: How often does it fire?
A: This means that if you need to add controls to a grid item that should fire a postback event, you should:
  1. Create the controls in ItemCreated event handler
  2. Bind them to data in ItemDataBound (if that's needed)
*** end excerpt ***

How does that work?  I assumed that in the ItemCreated event, I create the control as such where gridDataItem is the eventArg:

// RadGrid_ItemCreated event
HyperLink chartHyperLink = 
new HyperLink();  
chartHyperLink.Text = chartParameters;  
 
gridDataItem[gridColumn.UniqueName].Controls.Add(chartHyperLink); 

Shouldn't that new control now be in the ViewState and accessible from the next event RadGrid_ItemDataBound as such?

// RadGrid_ItemDataBound event
foreach
 (Control control in gridDataItem[gridColumn.UniqueName].Controls)  
{  
    // Get the control that I just created in the RadGrid_ItemCreated  
    if (control.ID == "chartHyperLink") // Or whatever ID I gave that control  
    {  
        HyperLink myHyperLink = (HyperLink)control;  
    }  

I don't see the control that I have created in the _ItemCreated, it does not make itself available in the _ItemDataBound event so how do I change the properties of the control I have made?


Next question...

*** begin excerpt ***
The changed made in the ItemCreated/ItemDataBound handlers will be persisted in the ViewState.
*** end excerpt ***

Umm, the data (e.g. gridDataItem[gridColumn.UniqueName].text) is persisted in ViewState but, any new controls that I create are not persisted in ViewState.  Any usage of

gridDataItem[gridColumn.UniqueName].Controls.Count always returns a 0.  How do I persist and find my controls that I have created in the _ItemCreated event in ViewState?

Thank you so much for your assistance!  I greatly appreciate your help.  :D

-Stacy

Tags
Grid
Asked by
Stacy
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Stacy
Top achievements
Rank 1
Robert Jakech
Top achievements
Rank 1
Share this question
or