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

RadGrid GridDropDownColumn value disappears

1 Answer 203 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Craig
Top achievements
Rank 1
Craig asked on 07 Feb 2013, 04:47 PM
Having trouble with RadGrid, My GridDropDownColumn data is loaded dynamically on itemdatabound but when you change the selected item or update the grid which causes an error then all the values disappear. Have tried several ways to stop this happening but nothing appears to be working

<asp:Content ID="Content2" ContentPlaceHolderID="ContentMain" Runat="Server">
    <div class="twocol">
        <div class="colfull">
            <div class="panel">
                <asp:Panel ID="RefinePanel" runat="server">
                    <span>Global:</span>
                    <asp:DropDownList runat="server" ID="GlobalDropDown" OnSelectedIndexChanged="Global_Change" OnPreRender="Global_Load" AutoPostBack="true">
                        <asp:ListItem Value="1">Global</asp:ListItem>
                        <asp:ListItem Value="0">Non-Global</asp:ListItem>
                        <asp:ListItem Value="2">All</asp:ListItem>
                    </asp:DropDownList>
                    <span>ReadOnly:</span>
                    <asp:DropDownList runat="server" ID="ReadOnlyDropDown" OnSelectedIndexChanged="ReadOnly_Change" OnPreRender="ReadOnly_Load" AutoPostBack="true">
                        <asp:ListItem Value="0">Editable</asp:ListItem>
                        <asp:ListItem Value="1">Read Only</asp:ListItem>
                        <asp:ListItem Value="2">All</asp:ListItem>
                    </asp:DropDownList>
                </asp:Panel>
            </div>
        </div>
    </div>
    <div class="twocol">
        <div class="cole">
            <div class="panel">
                <asp:ValidationSummary runat="server" ID="AttributeValidationSummary" DisplayMode="BulletList" HeaderText="Error(s)" ValidationGroup="Attribute" CssClass="validationSummary" />
                <telerik:RadGrid ID="AttributeGrid" runat="server" Width="100%"
                    AllowPaging="true"
                    PageSize="20"
                    AllowMultiRowEdit="false"
                    AllowMultiRowSelection="false"
                    AutoGenerateColumns="False"
                    EnableLinqExpressions="false"
                    GridLines="None"
 
                    OnItemCreated="AttributeGrid_ItemCreated"
                    OnSelectedIndexChanged="AttributeGrid_SelectedIndexChanged"
                    OnItemDataBound="AttributeGrid_ItemDataBound"
                    OnNeedDataSource="AttributeGrid_NeedDataSource"
                    OnDeleteCommand="AttributeGrid_DeleteCommand"
                    OnInsertCommand="AttributeGrid_InsertCommand"
                    OnUpdateCommand="AttributeGrid_UpdateCommand"
                    >
                    <PagerStyle Mode="NextPrevAndNumeric" />
                    <MasterTableView AutoGenerateColumns="false" DataKeyNames="ProductAttributeDefKey" InsertItemDisplay="Bottom" CommandItemDisplay="Bottom" EditMode="InPlace">
                        <Columns>
                            <telerik:GridBoundColumn DataField="ProductAttributeDefKey" HeaderText="Definition Key" SortExpression="ProductAttributeDefKey" UniqueName="ProductAttributeDefKey">
                                <ItemStyle CssClass="textColumn" />
                                <HeaderStyle CssClass="textColumn" />
                            </telerik:GridBoundColumn>
 
                            <telerik:GridBoundColumn DataField="ProductAttributeDefKey" HeaderText="ProductAttributeDefKeyOri" SortExpression="ProductAttributeDefKeyOri" UniqueName="ProductAttributeDefKeyOri" ReadOnly="true" ForceExtractValue="Always" Visible="false">
                            </telerik:GridBoundColumn>
                             
                            <telerik:GridBoundColumn DataField="Name" HeaderText="Name" SortExpression="Name" UniqueName="Name">
                                <ItemStyle CssClass="textColumn" />
                                <HeaderStyle CssClass="textColumn" />
                            </telerik:GridBoundColumn>
 
                            <telerik:GridDropDownColumn HeaderText="Data Type" DataField="AttributeDataType" UniqueName="AttributeDataType" DropDownControlType="DropDownList">
                                <ItemStyle CssClass="dropColumn" />
                                <HeaderStyle CssClass="dropColumn" />
                            </telerik:GridDropDownColumn>
 
                            <telerik:GridBoundColumn DataField="ImageIcon" HeaderText="Icon" SortExpression="ImageIcon" UniqueName="ImageIcon">
                                <ItemStyle CssClass="textColumn" />
                                <HeaderStyle CssClass="textColumn" />
                            </telerik:GridBoundColumn>
 
                            <telerik:GridCheckBoxColumn DataField="IsGlobal" HeaderText="Global" SortExpression="IsGlobal" UniqueName="IsGlobal">
                                <ItemStyle CssClass="checkColumn" />
                                <HeaderStyle CssClass="checkColumn" />
                            </telerik:GridCheckBoxColumn>
 
                            <telerik:GridCheckBoxColumn DataField="IsReadOnly" HeaderText="Read Only" SortExpression="IsReadOnly" UniqueName="IsReadOnly" ReadOnly="true" ForceExtractValue="Always">
                                <ItemStyle CssClass="checkColumn" />
                                <HeaderStyle CssClass="checkColumn" />
                            </telerik:GridCheckBoxColumn>
 
                            <telerik:GridCheckBoxColumn DataField="IsStyle" HeaderText="Style" SortExpression="IsStyle" UniqueName="IsStyle">
                                <ItemStyle CssClass="checkColumn" />
                                <HeaderStyle CssClass="checkColumn" />
                            </telerik:GridCheckBoxColumn>
 
                            <telerik:GridCheckBoxColumn DataField="PluOnly" HeaderText="PLU Only" SortExpression="PluOnly" UniqueName="PluOnly">
                                <ItemStyle CssClass="checkColumn" />
                                <HeaderStyle CssClass="checkColumn" />
                            </telerik:GridCheckBoxColumn>
 
                            <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
                                <ItemStyle CssClass="editColumn" />
                                <HeaderStyle CssClass="editColumn" />
                            </telerik:GridEditCommandColumn>
                        </Columns>
                        <EditFormSettings>
                            <EditColumn ButtonType="ImageButton" />
                        </EditFormSettings>
                    </MasterTableView>
                    <ValidationSettings CommandsToValidate="PerformInsert,Update" ValidationGroup="Attribute" EnableModelValidation="true" />
                    <ClientSettings EnablePostBackOnRowClick="true">
                        <Selecting AllowRowSelect="True" />
                    </ClientSettings>
                    <PagerStyle Mode="NextPrevAndNumeric" PageButtonCount="5" HorizontalAlign="Center" Width="100%" ShowPagerText="true" />
                </telerik:RadGrid>
                <telerik:GridCheckBoxColumnEditor ID="GridCheckBoxColumnEditor1" runat="server" CheckBoxStyle-BorderWidth="1" />
            </div>
        </div>
        <div class="colf">
            <asp:Panel runat="server" ID="LookupPanel" CssClass="panel" Visible="false">
                <h2 runat="server" id="LookupTitle">Users</h2>
                <p>Click a lookup attribute view/edit look up values</p>
                <asp:ValidationSummary runat="server" ID="LookupValidationSummary" DisplayMode="BulletList" HeaderText="Error(s)" ValidationGroup="LookupValidation" CssClass="validationSummary" />
                <asp:TextBox runat="server" ID="DefKey" TextMode="SingleLine" Visible="false"></asp:TextBox>
                <telerik:RadGrid ID="LookupGrid" runat="server" Width="100%"
                    AllowPaging="false"
                    AllowMultiRowEdit="false"
                    AllowMultiRowSelection="false"
                    AutoGenerateColumns="false"
                    EnableLinqExpressions="false"
                    GridLines="None"
                    PageSize="50"
                    OnItemCreated="LookupGrid_ItemCreated"
                    OnItemDataBound="LookupGrid_ItemDataBound"
                    OnItemCommand="LookupGrid_ItemCommand"
                    OnNeedDataSource="LookupGrid_NeedDataSource"
                    OnDeleteCommand="LookupGrid_DeleteCommand"
                    OnInsertCommand="LookupGrid_InsertCommand"
                    OnUpdateCommand="LookupGrid_UpdateCommand"
                    >
                    <PagerStyle Mode="NextPrevAndNumeric" />
                    <MasterTableView Width="100%" InsertItemDisplay="Bottom" DataKeyNames="ProductAttributeLookupId,ProductAttributeDefKey" CommandItemDisplay="Bottom" EditMode="InPlace" AutoGenerateColumns="false">
                        <Columns>
                            <telerik:GridBoundColumn DataField="ProductAttributeLookupId" HeaderText="ProductAttributeLookupId" SortExpression="ProductAttributeLookupId" UniqueName="ProductAttributeLookupId" Visible="false">
                            </telerik:GridBoundColumn>
 
                            <telerik:GridBoundColumn DataField="ProductAttributeDefKey" HeaderText="ProductAttributeDefKey" SortExpression="ProductAttributeDefKey" UniqueName="ProductAttributeDefKey" Visible="false">
                            </telerik:GridBoundColumn>
 
                            <telerik:GridBoundColumn DataField="VarcharValue" HeaderText="Value" SortExpression="VarcharValue" UniqueName="VarcharValue">
                            </telerik:GridBoundColumn>
 
                            <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
                                <ItemStyle CssClass="editColumn" />
                                <HeaderStyle CssClass="editColumn" />
                            </telerik:GridEditCommandColumn>
 
                            <telerik:GridButtonColumn ConfirmText="Delete Value?" ButtonType="ImageButton" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">
                                <HeaderStyle Width="20px" />
                                <ItemStyle HorizontalAlign="Center" CssClass="MyImageButton" />
                            </telerik:GridButtonColumn>
                        </Columns>
                        <NoRecordsTemplate>
                            <p class="center">No Values Found</p>
                        </NoRecordsTemplate>
                        <EditFormSettings CaptionFormatString="Edit Value" InsertCaption="Add Value">
                            <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
                            <EditColumn ButtonType="ImageButton" InsertText="Add Value" UpdateText="Edit Value" UniqueName="EditCommandColumn" CancelText="Cancel Edit"></EditColumn>
                            <FormTableButtonRowStyle HorizontalAlign="Right" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
                        </EditFormSettings>
                        <CommandItemSettings AddNewRecordText="Add Value" />
                    </MasterTableView>
                    <ValidationSettings CommandsToValidate="PerformInsert,Update" ValidationGroup="LookupValidation" />
                </telerik:RadGrid>
            </asp:Panel>
        </div>
    </div>
 
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="AttributeGrid">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="AttributeGrid" />
                    <telerik:AjaxUpdatedControl ControlID="LookupPanel" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="LookupGrid">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="LookupGrid" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
</asp:Content>

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Telerik.Web.UI;
using System.Text.RegularExpressions;
using JD.Common.Pim.DAL;
using JD.Common.Pim.DAL.DatabaseSpecific;
using JD.Common.Pim.DAL.EntityClasses;
using JD.Common.Pim.DAL.HelperClasses;
using JD.Common.Pim.DAL.FactoryClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using System.Collections.Specialized;
 
namespace JD.FeedManager.Pim.Website.Admin
{
    public partial class AttributeEditor : System.Web.UI.Page
    {
        static ConfigHandler commonConfig = ConfigUtils.GetConfig();
        DataAccessAdapter sqlAdapter = commonConfig.PimConfig.DBAdapter();
        Boolean writePermissions = false;
 
        Boolean? showGlobal = null; //default show all
        Boolean? showReadOnly = false; //default show editable
         
        protected void Page_Load(object source, EventArgs e)
        {
            Options_Load();
 
            writePermissions = PIMSession.Current.Write;
            Permissions_Load();
 
            if (!IsPostBack)
            {
                 
            }
        }
 
        protected void Page_LoadComplete(object source, EventArgs e)
        {
 
        }
 
        protected void Options_Load()
        {
            Int32 showGlobalTemp;
            if (Int32.TryParse(Request["glo"], out showGlobalTemp))
            {
                if (showGlobalTemp == 0)
                {
                    showGlobal = false;
                }
                else if (showGlobalTemp == 1)
                {
                    showGlobal = true;
                }
                else if (showGlobalTemp == 2)
                {
                    showGlobal = null;
                }
            }
 
            Int32 showReadOnlyTemp;
            if (Int32.TryParse(Request["rdo"], out showReadOnlyTemp))
            {
                if (showReadOnlyTemp == 0)
                {
                    showReadOnly = false;
                }
                else if (showReadOnlyTemp == 1)
                {
                    showReadOnly = true;
                }
                else if (showReadOnlyTemp == 2)
                {
                    showReadOnly = null;
                }
            }
        }
 
        protected void Permissions_Load()
        {
            if (!writePermissions)
            {
                AttributeGrid.Columns.FindByUniqueName("EditCommandColumn").Visible = false;
                //AttributeGrid.Columns.FindByUniqueName("DeleteColumn").Visible = false;
                AttributeGrid.MasterTableView.CommandItemDisplay = Telerik.Web.UI.GridCommandItemDisplay.None;
            }
        }
 
        protected void ReadOnly_Load(object source, EventArgs e)
        {
            if (showReadOnly == false)
            {
                ReadOnlyDropDown.SelectedValue = "0";
            }
            else if (showReadOnly == true)
            {
                ReadOnlyDropDown.SelectedValue = "1";
            }
            else if (showReadOnly == null)
            {
                ReadOnlyDropDown.SelectedValue = "2";
            }
        }
 
        protected void ReadOnly_Change(object source, EventArgs e)
        {
            DropDownList dropdown = (DropDownList)source;
            Int32 show = Convert.ToInt32(dropdown.SelectedValue);
 
            NameValueCollection parameters = new NameValueCollection(Request.QueryString);
            parameters.Remove("rdo");
            parameters.Set("rdo", Convert.ToString(show));
 
            Response.Redirect(Request.Url.AbsolutePath + "?" + General.ConstructQueryString(parameters));
        }
 
        protected void Global_Load(object source, EventArgs e)
        {
            if (showGlobal == false)
            {
                GlobalDropDown.SelectedValue = "0";
            }
            else if (showGlobal == true)
            {
                GlobalDropDown.SelectedValue = "1";
            }
            else if (showGlobal == null)
            {
                GlobalDropDown.SelectedValue = "2";
            }
        }
 
        protected void Global_Change(object source, EventArgs e)
        {
            DropDownList dropdown = (DropDownList)source;
            Int32 show = Convert.ToInt32(dropdown.SelectedValue);
 
            NameValueCollection parameters = new NameValueCollection(Request.QueryString);
            parameters.Remove("glo");
            parameters.Set("glo", Convert.ToString(show));
 
            Response.Redirect(Request.Url.AbsolutePath + "?" + General.ConstructQueryString(parameters));
        }
 
        protected void AttributeGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            RadGrid grid = source as RadGrid;
            grid.DataSource = RetrievalProcedures.ProcProductAttributeDefSelect(showGlobal, showReadOnly, sqlAdapter);
        }
 
        protected void AttributeGrid_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
 
            try
            {
                String productAttributeDefKey = Convert.ToString(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ProductAttributeDefKey"]);
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeDefDelete(productAttributeDefKey, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                AttributeGrid.Controls.Add(new LiteralControl("Unable to delete attribute. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void AttributeGrid_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
 
            try
            {
                String productAttributeDefKey = (editedItem["ProductAttributeDefKey"].Controls[0] as TextBox).Text;
                String productAttributeDefKeyOri = (editedItem["ProductAttributeDefKeyOri"].Controls[0] as TextBox).Text;
                String name = (editedItem["Name"].Controls[0] as TextBox).Text;
                Int32 attributeDataType = Convert.ToInt32((editedItem["AttributeDataType"].Controls[0] as DropDownList).SelectedValue);
                String imageIcon = (editedItem["ImageIcon"].Controls[0] as TextBox).Text;
                Boolean global = (editedItem["IsGlobal"].Controls[0] as CheckBox).Checked;
                Boolean readOnly = (editedItem["IsReadOnly"].Controls[0] as CheckBox).Checked;
                Boolean style = (editedItem["IsStyle"].Controls[0] as CheckBox).Checked;
                Boolean pluOnly = (editedItem["PluOnly"].Controls[0] as CheckBox).Checked;
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeDefUpdate(productAttributeDefKey, productAttributeDefKeyOri, name, attributeDataType, imageIcon, global, readOnly, style, pluOnly, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                AttributeGrid.Controls.Add(new LiteralControl("Unable to update attribute. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void AttributeGrid_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataInsertItem insertedItem = (GridDataInsertItem)e.Item;
 
            try
            {
                String productAttributeDefKey = (insertedItem["ProductAttributeDefKey"].Controls[0] as TextBox).Text;
                String name = (insertedItem["Name"].Controls[0] as TextBox).Text;
                Int32 attributeDataType = Convert.ToInt32((insertedItem["AttributeDataType"].Controls[0] as DropDownList).SelectedValue);
                String imageIcon = (insertedItem["ImageIcon"].Controls[0] as TextBox).Text;
                Boolean global = (insertedItem["IsGlobal"].Controls[0] as CheckBox).Checked;
                Boolean readOnly = (insertedItem["IsReadOnly"].Controls[0] as CheckBox).Checked;
                Boolean style = (insertedItem["IsStyle"].Controls[0] as CheckBox).Checked;
                Boolean pluOnly = (insertedItem["PluOnly"].Controls[0] as CheckBox).Checked;
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeDefInsert(productAttributeDefKey, name, attributeDataType, imageIcon, global, readOnly, style, pluOnly, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                AttributeGrid.Controls.Add(new LiteralControl("Unable to insert attribute. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void AttributeGrid_SelectedIndexChanged(object source, EventArgs e)
        {
            var dataItem = AttributeGrid.SelectedItems[0] as GridDataItem;
            LookupPanel.Visible = false;
            LookupTitle.InnerText = "Lookup Values";
 
            if (dataItem != null)
            {
                //get name and id
                var id = dataItem["ProductAttributeDefKey"].Text;
                var name = dataItem["Name"].Text;
                var datatype = dataItem["AttributeDataType"].Text;
 
                if (datatype == "Lookup List")
                {
                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        LookupTitle.InnerText = "Lookup Values (" + name + ")";
                    }
 
                    LookupPanel.Visible = true;
                    DefKey.Text = Convert.ToString(id);
                }
                else
                {
                    DefKey.Text = Convert.ToString(id);
                }
                LookupGrid.Rebind();
 
                //data type display fix
                Int32 selectedIndex = Convert.ToInt32(AttributeGrid.SelectedIndexes[0]);
                AttributeGrid.Rebind();
                AttributeGrid.MasterTableView.Items[selectedIndex].Selected = true;
            }
        }
 
        protected void AttributeGrid_ItemCreated(object source, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                GridEditableItem item = e.Item as GridEditableItem;
 
                GridTextBoxColumnEditor editor1 = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("Name");
                editor1.TextBoxControl.ID = "ID1_for_validation";
                GridTextBoxColumnEditor editor2 = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ProductAttributeDefKey");
                editor2.TextBoxControl.ID = "ID2_for_validation";
                GridDropDownColumnEditor editor3 = (GridDropDownColumnEditor)item.EditManager.GetColumnEditor("AttributeDataType");
 
                //String currDefKey = (String)item.GetDataKeyValue("ProductAttributeDefKey");
 
                //Name Validation
                TableCell cell1 = (TableCell)editor1.TextBoxControl.Parent;
 
                RequiredFieldValidator validator1 = new RequiredFieldValidator();
                validator1.ControlToValidate = editor1.TextBoxControl.ID;
                validator1.ErrorMessage = "Name Required";
                validator1.Text = "*";
                validator1.ValidationGroup = "Attribute";
                cell1.Controls.Add(validator1);
                RadAjaxManager1.AjaxSettings.AddAjaxSetting(validator1, AttributeGrid);
 
                //Definition Key Validation
                TableCell cell2 = (TableCell)editor2.TextBoxControl.Parent;
 
                RequiredFieldValidator validator2 = new RequiredFieldValidator();
                validator2.ControlToValidate = editor2.TextBoxControl.ID;
                validator2.ErrorMessage = "Definition Key Required";
                validator2.Text = "*";
                validator2.ValidationGroup = "Attribute";
                cell2.Controls.Add(validator2);
                RadAjaxManager1.AjaxSettings.AddAjaxSetting(validator2, AttributeGrid);
 
                //Data Type Validation
                DropDownList dropDownList1 = item["AttributeDataType"].Controls[0] as DropDownList;
                TableCell cell3 = (TableCell)editor3.ContainerControl;
 
                RequiredFieldValidator validator3 = new RequiredFieldValidator();
                validator3.ControlToValidate = dropDownList1.ID;
                validator3.ErrorMessage = "Data Type Required";
                validator3.Text = "*";
                validator3.ValidationGroup = "Attribute";
                cell3.Controls.Add(validator3);
                RadAjaxManager1.AjaxSettings.AddAjaxSetting(validator3, AttributeGrid);
            }
        }
 
        protected void AttributeGrid_ItemDataBound(object source, GridItemEventArgs e)
        {
            if (e.Item.IsInEditMode && e.Item is GridEditableItem)
            {
                GridEditableItem editItem = e.Item as GridEditableItem;
                GridEditManager editMgr = editItem.EditManager;
                GridDropDownListColumnEditor typeEditor = editMgr.GetColumnEditor("AttributeDataType") as GridDropDownListColumnEditor;
 
                typeEditor.DataSource = AttributeDataTypes.GetTypes();
                typeEditor.DataTextField = "Name";
                typeEditor.DataValueField = "Id";
                typeEditor.DataBind();
 
                DropDownList ddList = typeEditor.DropDownListControl;
                ddList.Items.Insert(0, new ListItem("Select a data type...", ""));
 
                string s = DataBinder.Eval(editItem.DataItem, "AttributeDataType").ToString();
                typeEditor.SelectedValue = s;
 
                if (e.Item is GridDataInsertItem)
                {
                    ImageButton InsertButton = (ImageButton)editItem.FindControl("PerformInsertButton");
                    InsertButton.ValidationGroup = "Attribute";
                    InsertButton.CausesValidation = true;
                     
                }
                else
                {
                    //disable drop down in edit mode
                    typeEditor.DropDownListControl.Enabled = false;
                     
                    ImageButton updateButton = (ImageButton)editItem.FindControl("UpdateButton");
                    updateButton.ValidationGroup = "Attribute";
                    updateButton.CausesValidation = true;
                }
            }
 
            if ((e.Item is GridDataItem) && !e.Item.IsInEditMode)
            {
                //disable and hide edit/delete buttons if read only attribute
                Boolean readOnly = (Boolean)DataBinder.Eval(e.Item.DataItem, "IsReadOnly");
                if (readOnly) { readOnly = false; } else { readOnly = true; }
 
                GridDataItem item = (GridDataItem)e.Item;
                ((ImageButton)item["EditCommandColumn"].Controls[0]).Enabled = readOnly;
                ((ImageButton)item["EditCommandColumn"].Controls[0]).Visible = readOnly;
 
                foreach (DataRow row in AttributeDataTypes.GetTypes().Rows)
                {
                    if((Int32)row["Id"] == (Int32)DataBinder.Eval(e.Item.DataItem, "AttributeDataType"))
                    {
                        item["AttributeDataType"].Text = (String)row["Name"];
                    }
                }
            }
 
        }
 
        protected void LookupGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            RadGrid grid = source as RadGrid;
            String defKey = null;
            if (!String.IsNullOrWhiteSpace(DefKey.Text))
            {
                defKey = DefKey.Text;
            }
            if (!String.IsNullOrWhiteSpace(defKey))
            {
                grid.DataSource = RetrievalProcedures.ProcProductAttributeLookupSelect(defKey, sqlAdapter);
            }
        }
 
        protected void LookupGrid_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
 
            try
            {
                Int32 productAttributeLookupId = Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ProductAttributeLookupId"]);
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeLookupDelete(productAttributeLookupId, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                LookupGrid.Controls.Add(new LiteralControl("Unable to delete value. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void LookupGrid_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
 
            try
            {
                Int32 productAttributeLookupId = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ProductAttributeLookupId"]);
                String varcharValue = (editedItem["VarcharValue"].Controls[0] as TextBox).Text;
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeLookupUpdate(varcharValue, productAttributeLookupId, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                LookupGrid.Controls.Add(new LiteralControl("Unable to update value. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void LookupGrid_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridDataInsertItem insertedItem = (GridDataInsertItem)e.Item;
 
            try
            {
                String productAttributeDefKey = Convert.ToString((insertedItem["ProductAttributeDefKey"].Controls[0] as TextBox).Text);
                String varcharValue = Convert.ToString((insertedItem["VarcharValue"].Controls[0] as TextBox).Text);
                if (writePermissions)
                {
                    ActionProcedures.ProcProductAttributeLookupInsert(productAttributeDefKey, varcharValue, sqlAdapter);
                }
            }
            catch (Exception ex)
            {
                LookupGrid.Controls.Add(new LiteralControl("Unable to insert value. Reason: " + ex.Message));
                e.Canceled = true;
            }
        }
 
        protected void LookupGrid_ItemDataBound(object source, GridItemEventArgs e)
        {
            if (e.Item.IsInEditMode && e.Item is GridEditableItem)
            {
                if (e.Item is GridDataInsertItem)
                {
                    GridEditableItem editItem = (GridEditableItem)e.Item;
                    ImageButton InsertButton = (ImageButton)editItem.FindControl("PerformInsertButton");
                    InsertButton.ValidationGroup = "LookupValidation";
                    InsertButton.CausesValidation = true;
                }
                else
                {
                    GridEditableItem editItem = (GridEditableItem)e.Item;
                    ImageButton updateButton = (ImageButton)editItem.FindControl("UpdateButton");
                    updateButton.ValidationGroup = "LookupValidation";
                    updateButton.CausesValidation = true;
                }
            }
        }
 
        protected void LookupGrid_ItemCreated(object source, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                GridEditableItem item = e.Item as GridEditableItem;
 
                //Name Validation
                GridTextBoxColumnEditor editor1 = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("VarcharValue");
                TableCell cell1 = (TableCell)editor1.TextBoxControl.Parent;
 
                RequiredFieldValidator validator1 = new RequiredFieldValidator();
                editor1.TextBoxControl.ID = "ID1_for_validation";
                validator1.ControlToValidate = editor1.TextBoxControl.ID;
                validator1.ErrorMessage = "Value Required";
                validator1.Text = "*";
                validator1.ValidationGroup = "LookupValidation";
                cell1.Controls.Add(validator1);
                RadAjaxManager1.AjaxSettings.AddAjaxSetting(validator1, LookupGrid);
            }
        }
 
        protected void LookupGrid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                // cancel the default operation
                e.Canceled = true;
                //GridDataItem item = (GridDataItem)e.Item;
 
                //Prepare an IDictionary with values
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();
                newValues["ProductAttributeDefKey"] = DefKey.Text;
 
                //Insert the item and rebind
                e.Item.OwnerTableView.InsertItem(newValues);
            }
        }
    }
}


1 Answer, 1 is accepted

Sort by
0
Marin
Telerik team
answered on 12 Feb 2013, 02:42 PM
Hi,

 I am attaching a sample page based on your code snippets which should work properly when the grid is in edit mode. The only problem in the code that I noticed is that you set different IDs for the textbox editor controls in the ItemCreated event. This is not necessary because the controls already have autogenerated IDs and changing them might cause problems when the the grid extracts the values for edit mode.

You can have a look at the attache sample page. For simplicity actual persisting of the data is not implemented.

Kind regards,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
Craig
Top achievements
Rank 1
Answers by
Marin
Telerik team
Share this question
or