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

Cancelling grid insert event causes dynamic columns to disappear

1 Answer 107 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Scott Bedard
Top achievements
Rank 1
Scott Bedard asked on 07 Jan 2009, 07:36 PM
I have a grid where I add dynamically created columns when a user starts an insert.

When the user actually does insert I set 'e.Canceled = true' to simulate a server side validation error. The dynamic columns disappear in the insert row. Notice the region combo box is still displayed because it is declaritive. How can I get the grid to show the columns to the user when the event is cancelled?

Page Code

 

using System;  
using System.Collections.Generic;  
using System.Data;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using Telerik.Web.UI;  
 
namespace ITemplateTest  
{  
    public partial class _Default : Page  
    {  
        private bool isInserting = false;  
 
        protected void Page_Load(object sender, EventArgs e)  
        {  
              
 
            var dict = new DataTable();  
            dict.Columns.Add("Region");  
            dict.Rows.Add("Region1");  
            dict.Rows.Add("Region2");  
 
            TestGrid.DataSource = dict;  
            TestGrid.DataBind();  
 
        }  
 
        protected void TestGrid_ItemCommand(object source, GridCommandEventArgs e)  
        {  
            switch (e.CommandName)  
            {  
                case RadGrid.InitInsertCommandName:  
                    var dateTemplate = new DatePickerTemplate();  
                    var dateColumn = new GridTemplateColumn { EditItemTemplate = dateTemplateHeaderText = "Test Date" };  
                    TestGrid.Columns.AddAt(TestGrid.Columns.Count, dateColumn);  
 
                    var comboTemplate = new ComboBoxTemplate();  
                    var comboColumn = new GridTemplateColumn { EditItemTemplate = comboTemplateHeaderText = "Test Combo" };  
                    TestGrid.Columns.AddAt(TestGrid.Columns.Count, comboColumn);  
 
                    TestGrid.ShowHeader = false;  
                    isInserting = true;  
                    break;  
                case RadGrid.CancelCommandName:  
                    isInserting = false;  
                    TestGrid.Columns.RemoveAt(1);  
                    TestGrid.ShowHeader = true;  
                    break;  
                case RadGrid.PerformInsertCommandName:  
                    isInserting = true;  
                    e.Canceled = true;  
                    break;  
 
 
            }  
              
 
        }  
 
        protected void TestGrid_ItemDataBound(object sender, GridItemEventArgs e)  
        {  
 
            if (e.Item == null) return;  
 
            if (isInserting && e.Item is GridDataItem)  
            {  
                //Merge the cells that have been inserted with the name cell.  
                var numOfRequired = 2;  
 
                e.Item.Cells[0].ColumnSpan = numOfRequired + 1;  
 
                for (var i = 1; i <= numOfRequired; i++)  
                {  
                    e.Item.Cells.RemoveAt(e.Item.Cells.Count - 1);  
                }  
            }  
 
            if (!isInserting && e.Item is GridDataItem)  
            {  
                //Set the column span to the correct value since it may have been altered by an insert  
                e.Item.Cells[0].ColumnSpan = 1;  
            }  
        }  
    }  
 
    class DatePickerTemplate : ITemplate  
    {  
        public void InstantiateIn(Control container)  
        {  
            var ctl = new RadDatePicker  
            {  
                SelectedDate = DateTime.Now  
            };  
            ctl.DateInput.Attributes.Add("FactID", "FactIDValue");  
            ctl.DateInput.Attributes.Add("HiddenFieldID", "HiddenFieldIDValue");  
            ctl.DateInput.ClientEvents.OnValueChanged = "DatePicker_Changed";  
            container.Controls.Add(ctl);  
        }  
    }  
 
    public class ComboBoxTemplate : ITemplate  
    {  
 
        public void InstantiateIn(Control container)  
        {  
            var ctl = new RadComboBox()  
            {  
                ID = "RadComboBox" 
            };  
 
            //foreach(DataRow row in dt.Rows)  
            //{  
            //    ctl.Items.Add(new RadComboBoxItem(row[textField].ToString(), row[valueField].ToString()));  
            //}  
 
            //if (noValue != null)  
            //    ctl.Items.Insert(0, new RadComboBoxItem(noValue, noValue_Value));  
 
            //ctl.Attributes.Add("onChange", string.Format("{0}(this);", jScriptFunction));  
            ctl.Attributes.Add("FactID", "SomeID");  
            ctl.Attributes.Add("HiddenFieldID", "SomeOtherID");  
 
            container.Controls.Add(ctl);  
        }  
    }  


ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ITemplateTest._Default" %> 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %> 
<%@ Import Namespace="BusinessGlossary"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server">  
    <title>Test Page</title> 
</head> 
<body> 
    <form id="form1" runat="server">     
   <div id="ScriptDiv" runat="server"<!-- did this because of asp.net code sections failing --> 
    <!-- TODO: SEB - Move to .js file --> 
            <script type="text/javascript">  
              
              var tStart = null;  
              var nodeAdditionButton = null;   
              var pairDelimiter = '|';   
              var nameValueDelimiter = '~';      
                
              function disableEnterKey()  
             {  
                 if (window.event.keyCode == 13)   
                    {  
                        event.returnValue=false;   
                        event.cancel = true;  
                    }  
             }          
              
             function requestStart(sender, eventArgs)  
               {     
                    tStart = new Date();  
                    document.body.style.cursor = 'wait';  
               }  
                
               function responseEnd(sender, eventArgs)  
               {  
                   document.body.style.cursor = 'default';  
                     
                   if (nodeAdditionButton != null) {  
                     nodeAdditionButton.style.cursor = 'default';  
                     nodeAdditionButton = null;  
                     }  
                     
                   //Comment in final per Eddie 10/9  
                   var tDate = new Date();  
                   var tDiff = tDate.getTime() - tStart.getTime();  
                     
                   var tTimer = new Date();  
                   tTimer.setTime(tDiff);  
                     
                   var label = document.getElementById("TimingLabel");  
                   label.innerText = tTimer.getSeconds() + "." + tTimer.getMilliseconds() + " seconds";  
                    //TODO: Use is naming  
                    if (openExcelWindow) {  
                        openExportWindow();  
                        openExcelWindow = false;  
                    }  
                      
                      
              }  
                
            // This function will open a window and run the screen to export to excel  
            function openExportWindow() {  
               w = window.open('ExportToExcel.aspx', 'exportToExcel', 'height=450,width=700,status=yes,resizable,toolbar=no,menubar=no,location=no');    
               //setTimeout('w.close()', 5000);  
            }  
              
            var supressDropDownClosing = false;  
            var openExcelWindow = false;  
              
            function OnClientDropDownClosing(sender, eventArgs)  
            {  
                eventArgs.set_cancel(supressDropDownClosing);  
            }  
           
            function ExportToExcel(button)  
            {  
                  
                openExcelWindow = true;  
 
            }  
              
            //Fact Maintenance -- comment this  
            function FactDataTypeChanged(dataTypeDropDown, dataValidationTypeDropDownID)  
            {  
                var dataValidationTypeDropDown = document.getElementById(dataValidationTypeDropDownID);  
                var selectedValue = dataTypeDropDown[dataTypeDropDown.selectedIndex].text;  
                if (selectedValue == 'String' || selectedValue == 'Numeric')  
                {  
                    dataValidationTypeDropDown.disabled = false;  
                }  
                else  
                {     
                  
                    for (var itemIndex = 0; itemIndex < dataValidationTypeDropDown.length; itemIndex++)  
                    {     
                        if (dataValidationTypeDropDown[itemIndex].text == 'None') {  
                            dataValidationTypeDropDown.selectedIndex = itemIndex;  
                            break;  
                        }  
                    }  
                    dataValidationTypeDropDown.disabled = true;  
 
                }  
                
            }  
              
            function validateDateInput (input, args){  
                var message = "the value " + input.get_textBoxValue() + " is not a valid date.";  
                window.alert(message);  
                input.clear();  
                input.focus();  
            }  
 
            function DisableControls()  
            {  
                for (var i=0; i<document.forms[0].elements.length; i++)  
                {              
                    var obj = document.forms[0].elements[i];  
                    obj.disabled = true;  
                }  
            }  
              
            function EnableControls()  
            {  
                for (var i=0; i<document.forms[0].elements.length; i++)  
                {          
                    var obj = document.forms[0].elements[i];  
                    obj.disabled = false;  
                }  
            }  
 
            function DataElementTreeInputChanged(sender, eventArgs)  
            {  
                Tree_RadInputChanged(sender, eventArgs, 'dataElementTreeNodeFields', 'dataElementTreeUpdateValues');  
            }  
              
            function DataElementTreeComboBoxChanged(sender, eventArgs)  
            {  
                Tree_RadComboBoxChanged(sender, eventArgs, 'dataElementTreeNodeFields', 'dataElementTreeUpdateValues');  
            }  
              
            function ProcessTreeInputChanged(sender, eventArgs)  
            {  
                Tree_RadInputChanged(sender, eventArgs, 'processTreeNodeFields', 'processTreeUpdateValues');  
            }  
              
            function ProcessTreeComboBoxChanged(sender, eventArgs)  
            {  
                Tree_RadComboBoxChanged(sender, eventArgs, 'processTreeNodeFields', 'processTreeUpdateValues');  
            }  
              
            function ApplicationTreeInputChanged(sender, eventArgs)  
            {  
                Tree_RadInputChanged(sender, eventArgs, 'applicationTreeNodeFields', 'applicationTreeUpdateValues');  
            }  
              
            function ApplicationTreeComboBoxChanged(sender, eventArgs)  
            {  
                Tree_RadComboBoxChanged(sender, eventArgs, 'applicationTreeNodeFields', 'applicationTreeUpdateValues');  
             }  
      
            function Tree_RadInputChanged(sender, eventArgs, treeNodeFieldsHidden, treeValuesHidden)  
             {  
                var factTree = document.getElementById(treeNodeFieldsHidden);  
                var inputField = sender.get_element();  
                  
                nodeID = FindNodeIDByControlID(inputField.id, treeNodeFieldsHidden);  
                  
                var value = eventArgs.get_newValue();  
                  
                FieldValueChanged(nodeID, treeValuesHidden, value);  
 
             }  
 
            function Tree_RadComboBoxChanged(sender, eventArgs, treeNodeFieldsHidden, treeValuesHidden)  
             {  
                  
                var comboBoxInput = sender.get_element();  
                  
                nodeID = FindNodeIDByControlID(comboBoxInput.id, treeNodeFieldsHidden);  
                  
                var value = eventArgs.get_item().get_text();  
                  
                FieldValueChanged(nodeID, treeValuesHidden, value);  
             }  
               
             function FindNodeIDByControlID (controlID, treeNodeFieldsHidden)  
             {  
                var factTree = document.getElementById(treeNodeFieldsHidden);  
                var array = factTree.value.split(pairDelimiter);  
               var nodeID;  
                 
               for (i = 0; i < array.length; i++)  
                {  
                    var nameValuePair = array[i].split(nameValueDelimiter);  
                    if (nameValuePair.length = 2)   
                    {  
                        if (nameValuePair[0] == controlID)   
                        {  
                            nodeID = nameValuePair[1]  
                        }  
                    }  
                }  
                  
                return nodeID;  
               
             }  
 
             function Tree_ListBoxUpdated(nodeID, listBox, treeNodeFieldsHidden, treeValuesHidden)  
             {  
   
               var value = '';  
                 
                for(i = 0; i < listBox.length; i++)  
                {  
                    if (listBox[i].selected)  
                    {  
                        valuevalue = value + ',' + listBox[i].value;  
                    }  
                }  
                                 
                valuevalue = value.replace(/^\,/, '')  
                  
                FieldValueChanged(nodeID, treeValuesHidden, value);  
 
             }  
               
             function Tree_CheckBoxUpdated(nodeID, checkBoxID, checked, treeNodeFieldsHidden, treeValuesHidden)  
             {  
                var value;  
                if (checked)  
                    value = 'true';  
                else  
                    value = 'false';  
                      
                FieldValueChanged(nodeID, treeValuesHidden, value);  
             }  
               
             function CheckBoxChanged(checkBox, ID, hiddenFieldID)  
             {  
                var value;  
                if (checkBox.checked)  
                    value = 'true';  
                else  
                    value = 'false';  
                      
                FieldValueChanged(ID, hiddenFieldID, value);  
             }  
               
             function RadComboBoxChanged(comboBox)  
             {  
                  
                var value = comboBox.options(comboBox.selectedIndex).text;  
                  
                var ID = comboBox.getAttribute('FactID');  
                var hiddenFieldID = comboBox.getAttribute('HiddenFieldID');  
                      
                FieldValueChanged(ID, hiddenFieldID, value);  
             }  
               
             function RadDatePickerChanged(sender, eventArgs)  
             {  
                  var inputField = sender.get_element();  
                    
                  var value = eventArgs.get_newValue();  
                    
                  var ID = inputField.getAttribute('FactID');  
                  var hiddenFieldID = inputField.getAttribute('HiddenFieldID');  
                    
                  FieldValueChanged(ID, hiddenFieldID, value);  
             }  
               
             function RadTextBoxChanged(textBox)  
             {  
                    
                  var value = textBox.value;  
                    
                  var ID = textBox.getAttribute('FactID');  
                  var hiddenFieldID = textBox.getAttribute('HiddenFieldID');  
                    
                  FieldValueChanged(ID, hiddenFieldID, value);  
             }  
               
             function FieldValueChanged(valueID, hiddenTextBoxID, value)  
             {  
               
                //Look for previous values in string  
                var hiddenTextBox = document.getElementById(hiddenTextBoxID);  
                var valueArray = hiddenTextBox.value.split(pairDelimiter);  
                  
                var found = false;  
 
                for (i = 0; i < valueArray.length; i++)  
                {  
                    var nameValuePair = valueArray[i].split(nameValueDelimiter);  
                    if (nameValuePair.length = 2)   
                    {  
                        if (nameValuePair[0] == valueID)   
                        {  
                            var oldValue = nameValuePair[1];  
                            found = true;  
                        }  
                    }  
                }  
                  
                var pairsValue = hiddenTextBox.value;  
                if (found)  
                {  
                    pairsValuepairsValue = pairsValue.replace(valueID + nameValueDelimiter + oldValue, valueID + nameValueDelimiter + value);  
                }  
                else  
                {  
                    pairsValue += pairDelimiter + valueID + nameValueDelimiter +  value;  
                    pairsValuepairsValue = pairsValue.replace(/^\~/, '');  
                }  
                hiddenTextBox.value = pairsValue;  
 
             }  
               
             function ProcessNodeMultipleAction(button, controlToUse)  
             {  
               
                nodeAdditionButton = button;  
                button.style.cursor = 'wait';  
                  
                var control = document.getElementById(controlToUse);  
                  
                var newValue = 'NodeID:' + button.getAttribute('NodeID');  
                var newValuenewValue = newValue + ';CommandName:' + button.getAttribute('CommandName');  
                var newValuenewValue = newValue + ';GroupInstanceID:' + button.getAttribute('GroupInstanceID');  
                var newValuenewValue = newValue + ';FactInstanceID:' + button.getAttribute('FactInstanceID');  
                var newValuenewValue = newValue + ';ArtifactFactInstanceID:' + button.getAttribute('ArtifactFactInstanceID');  
                var newValuenewValue = newValue + ';ParentGroupID:' + button.getAttribute('ParentGroupID');  
                var newValuenewValue = newValue + ';FactID:' + button.getAttribute('FactID');  
 
                control.value = newValue; //This will trigger the text box text_changed event to fire..basically posting back for us.  
 
             }  
               
             function ClearDatePicker(radDatPicker)  
               {     
                    var datePicker = document.getElementById(radDatPicker);  
                   if (datePicker != null)  
                   {  
                    datePicker.Clear();  
                   }  
                   return false;  
               }  
                 
                            function DatePicker_Changed(sender, eventArgs)  
               {     
                     
                   return true;  
               }  
 
               function ClearControlSelections(nodeID, target, treeNodeFieldsHidden, treeValuesHidden)  
               {  
                    var control = document.getElementById(target);  
                    control.selectedIndex = -1;  
                    Tree_ListBoxUpdated(nodeID, control, treeNodeFieldsHidden, treeValuesHidden);  
              }  
                
              function SetRegionVisibility(dropdown, target)  
              {  
                
                    var targetDropDown = document.getElementById(target);      
                      
                    if (dropdown.selectedIndex != 0)  
                    {  
                        targetDropDown.disabled = true;  
                        for( var i=0limit=targetDropDown.options.length; i < limit; ++i )  
                        {  
                            targetDropDown.options[i].selected=false;  
                        }  
 
                    }  
                    else  
                         targetDropDown.disabled = false;  
                
              }  
                 
            </script> 
</div> 
    <div runat="server" id="TestGridDiv">  
    <telerik:RadScriptManager ID="RadScriptManager1" Runat="server">  
    </telerik:RadScriptManager> 
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">  
        <AjaxSettings> 
        <telerik:AjaxSetting AjaxControlID="TestGrid">  
        <UpdatedControls><telerik:AjaxUpdatedControl ControlID="TestGrid" /></UpdatedControls>  
        </telerik:AjaxSetting> 
        </AjaxSettings> 
        </telerik:RadAjaxManager> 
    </div> 
    <telerik:RadTabStrip ID="RadTabStrip1" runat="server" SelectedIndex="0" MultiPageID="RadMultiPage1">  
        <Tabs> 
            <telerik:RadTab runat="server" Text="Root RadTab1" Selected="True" PageViewID="RadPageView1">  
            </telerik:RadTab> 
            <telerik:RadTab runat="server" Text="Root RadTab2"  PageViewID="RadPageView2">  
            </telerik:RadTab> 
        </Tabs> 
    </telerik:RadTabStrip> 
     
   <telerik:RadMultiPage ID="RadMultiPage1" Runat="server">  
             <telerik:RadPageView ID="RadPageView2" Runat="server" Width="100%">  
        <telerik:RadDatePicker ID="RadDatePicker1" Runat="server">  
    </telerik:RadDatePicker> 
    </telerik:RadPageView> <telerik:RadPageView ID="RadPageView1" Runat="server" Width="100%">  
         <div id="TestGridPanel">  
<telerik:RadGrid ID="TestGrid" runat="server" AutoGenerateColumns="False"   
            GridLines="None" onitemcommand="TestGrid_ItemCommand"   
                onitemdatabound="TestGrid_ItemDataBound">  
<mastertableview commanditemdisplay="Top" editmode="EditForms">  
<norecordstemplate> 
        <asp:Label ID="ProcessFilterLabel" runat="server" Text="No processes found." /> 
    </norecordstemplate> 
    <Columns> 
    <telerik:GridTemplateColumn HeaderText="Region" UniqueName="region">  
        <EditItemTemplate> 
            <asp:ListBox ID="RegionListBox" runat="server"><asp:ListItem Text="Region" Value="Value"></asp:ListItem></asp:ListBox> 
          </EditItemTemplate> 
          <ItemTemplate>Hello</ItemTemplate> 
          </telerik:GridTemplateColumn> 
    </Columns> 
       <editformsettings> 
        <popupsettings scrollbars="None" /> 
    </editformsettings> 
</mastertableview> 
</telerik:RadGrid> 
</div> 
    </telerik:RadPageView> 
    </telerik:RadMultiPage> 
 
    </form> 
</body> 
</html> 
 

1 Answer, 1 is accepted

Sort by
0
Daniel
Telerik team
answered on 12 Jan 2009, 11:38 AM
Hello Scott,

RadGrid does not support mixing declarative grid columns with grid columns added dynamically at runtime. You should either create all the columns in the grid programmatically, or else define them all in the ASPX file.

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 (see below). That way, template controls are instantiated before the LoadViewState event of the page.

Programmatic creation

Regards,
Daniel
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
Tags
Grid
Asked by
Scott Bedard
Top achievements
Rank 1
Answers by
Daniel
Telerik team
Share this question
or