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

[Solved] RadComboBox In RadGrid not working

2 Answers 409 Views
Grid
This is a migrated thread and some comments may be shown as answers.
mark
Top achievements
Rank 1
mark asked on 24 Aug 2009, 08:32 AM
Hello all,

I am trying to include a combobox in a grid and not having much success.  I have tried two different approaches and both seem to be problematic.  I will include the approach for both and would gladly accept a solution for either.

Approach #1. Using Server Side OnLoad

 

 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TradeType.aspx.vb"  MasterPageFile="~/Eclipse.Master" Inherits="Eclipse3.TradeType" %> 
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %> 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentTopMenu" Runat="Server">  
    <table> 
        <tr> 
            <td> 
            Maintain Trade Types  
            </td> 
        </tr> 
    </table> 
</asp:Content> 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentMain" runat=server>  
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">  
        <AjaxSettings> 
            <telerik:AjaxSetting AjaxControlID="RadGrid1">  
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" /> 
                </UpdatedControls> 
            </telerik:AjaxSetting> 
        </AjaxSettings> 
    </telerik:RadAjaxManager> 
    <telerik:RadGrid ID="RadGrid1"   
        Width="100%" 
        AllowPaging="True"   
        PageSize="5" 
        AutoGenerateColumns="false" 
        AllowAutomaticDeletes="False" 
        AllowAutomaticInserts="False" 
        AllowAutomaticUpdates="False"    
        ShowStatusBar = "true" 
        runat="server"    
        AllowSorting="true"    
        ImagesPath="../images"    
        GridLines="None">  
      <MasterTableView Width="100%" DataKeyNames="nTradeTypeID" CommandItemDisplay="TopAndBottom" 
                AutoGenerateColumns="false" InsertItemDisplay="Top"   
                InsertItemPageIndexAction="ShowItemOnFirstPage" EditMode="InPlace" > 
                <Columns> 
                    <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn" ItemStyle-Width="10px" > 
                    </telerik:GridEditCommandColumn> 
                    <telerik:GridButtonColumn ConfirmText="Delete this Trade Type?" ConfirmDialogType="RadWindow" 
                        ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">  
                    </telerik:GridButtonColumn> 
                    <telerik:GridBoundColumn DataField="nTradeTypeID" UniqueName="nTradeTypeID" HeaderText="Trade Type ID" 
                        ReadOnly="true" Visible="false">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="sTradeTypeName" UniqueName="sTradeTypeName" HeaderText="Trade Type Name" Resizable="true">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridBoundColumn DataField="mUnitCost" UniqueName="mUnitCost" HeaderText="Unit Cost" Resizable="true" DataType="System.Decimal" DataFormatString="{0:c}">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridTemplateColumn UniqueName="UnitType" HeaderText="Unit Type" 
                        SortExpression="nUnitTypeId">  
                        <FooterTemplate>Template footer</FooterTemplate> 
                        <FooterStyle VerticalAlign="Middle" HorizontalAlign="Center" /> 
                        <ItemTemplate> 
                            <%#DataBinder.Eval(Container.DataItem, "sUnitTypeName")%> 
                        </ItemTemplate> 
                        <EditItemTemplate> 
                            <telerik:RadComboBox DataTextField="sUnitTypeName"   
                                DataValueField="nUnitTypeId" 
                                OnLoad="UnitTypeRadComboBox_OnLoad"   
                                SelectedValue='<%#DataBinder.Eval(Container.DataItem, "nUnitTypeId")%>' 
                                EnableLoadOnDemand="False" 
                                ID="UnitTypeRadComboBox"   
                                runat="server"   
                                Height="140px"   
                                Width="220px" > 
                            </telerik:RadComboBox> 
                        </EditItemTemplate> 
                    </telerik:GridTemplateColumn> 
                    <telerik:GridBoundColumn DataField="mAmount" UniqueName="mAmount" HeaderText="Amount" Resizable="true" DataType="System.Decimal" DataFormatString="{0:c}">  
                    </telerik:GridBoundColumn> 
                    <telerik:GridTemplateColumn HeaderText="bConcurrencyId" Visible="false" UniqueName="bConcurrencyId" SortExpression="bConcurrencyId" EditFormColumnIndex="1"  > 
                        <ItemTemplate> 
                            <asp:Label runat="server"   
                                ID="lbConcurrencyId"   
                                Text='<%# System.Convert.ToBase64String(Eval("bConcurrencyId")) %>' 
                                visible="false">  
                            </asp:Label> 
                        </ItemTemplate>   
                        <EditItemTemplate> 
                           <asp:TextBox runat="server"   
                                ID="tbConcurrencyId"   
                                Text='<%# System.Convert.ToBase64String(Eval("bConcurrencyId")) %>' 
                                visible="false">  
                            </asp:TextBox> 
                        </EditItemTemplate> 
                    </telerik:GridTemplateColumn> 
                </Columns> 
                <CommandItemSettings AddNewRecordText="Add new record" AddNewRecordImageUrl="../Images/AddRecord.gif" 
                    RefreshText="Refresh" RefreshImageUrl="../Images/Refresh.gif" /> 
            </MasterTableView> 
      <SortingSettings SortedBackColor="Azure" EnableSkinSortStyles="false" /> 
      <PagerStyle Mode="NextPrevAndNumeric"   /> 
      <FilterMenu EnableTheming="True">  
            <CollapseAnimation Duration="200" Type="OutQuint" /> 
      </FilterMenu> 
    </telerik:RadGrid> 
    <br /> 
   </asp:Content> 


*****************************************************************************************************************

 

 

 

Imports Eclipse3.BL  
Imports Eclipse3.Common  
Imports System  
Imports System.Web  
Imports System.Collections.ObjectModel  
Imports System.Collections.Generic  
Imports Telerik.Web.UI  
 
 
Partial Public Class TradeType  
    Inherits EclipsePageBase  
 
    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Load  
        Try 
            If Not IsPostBack Then 
                '*******************************************************************************************************  
                ' system call to determine if the current user has access to the requested page in the requested mode  
                '*******************************************************************************************************  
                AuthToPage()  
 
                '*******************************************************************************************************  
                ' retrieve the mode request from the query string and set the page accordingly.  
                '*******************************************************************************************************  
                Dim bPageIsReadOnly As Boolean = True 
                bPageIsReadOnly = Request.QueryString("PageIsReadOnly")  
 
                If bPageIsReadOnly = True Then 
                    RadGrid1.MasterTableView.Columns.FindByUniqueName("EditCommandColumn").Visible = False 
                    RadGrid1.MasterTableView.Columns.FindByUniqueName("DeleteColumn").Visible = False 
                    RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None  
                Else 
                    RadGrid1.MasterTableView.Columns.FindByUniqueName("EditCommandColumn").Visible = True 
                    RadGrid1.MasterTableView.Columns.FindByUniqueName("DeleteColumn").Visible = True 
                    RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.TopAndBottom  
                End If 
            End If 
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 
 
 
    '*************************************************************************************************************  
    ' this event is run each time the radgrid id databound  
    '*************************************************************************************************************  
    Protected Sub RadGrid1_NeedDataSource(ByVal source As ObjectByVal e As GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource  
        Try 
            Dim obj_TradeTypeCollection As New cls_TradeTypeCollection()  
            obj_TradeTypeCollection = obj_TradeTypeCollection.TradeTypeSelectAll()  
 
            RadGrid1.DataSource = obj_TradeTypeCollection  
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 
 
    Protected Sub UnitTypeRadComboBox_ItemsRequested(ByVal sender As ObjectByVal e As RadComboBoxItemsRequestedEventArgs)  
        '**********************************************************************  
        ' select all the unit types  
        '**********************************************************************  
        Dim obj_UnitTypeCollection As New cls_UnitTypeCollection()  
        obj_UnitTypeCollection = obj_UnitTypeCollection.UnitTypeSelectAll()  
 
        Dim comboBox As RadComboBox = DirectCast(sender, RadComboBox)  
        comboBox.Items.Clear()  
 
        For Each obj_UnitType As cls_UnitType In obj_UnitTypeCollection  
            Dim item As New RadComboBoxItem()  
            item.Text = obj_UnitType.sUnitTypeName  
            item.Value = obj_UnitType.nUnitTypeID  
            comboBox.Items.Add(item)  
        Next 
    End Sub 
 
    Protected Sub UnitTypeRadComboBox_OnLoad(ByVal sender As ObjectByVal e As System.EventArgs)  
        '**********************************************************************  
        ' select all the unit types  
        '**********************************************************************  
        Dim obj_UnitTypeCollection As New cls_UnitTypeCollection()  
        obj_UnitTypeCollection = obj_UnitTypeCollection.UnitTypeSelectAll()  
 
        Dim comboBox As RadComboBox = DirectCast(sender, RadComboBox)  
        comboBox.Items.Clear()  
 
        For Each obj_UnitType As cls_UnitType In obj_UnitTypeCollection  
            Dim item As New RadComboBoxItem()  
            item.Text = obj_UnitType.sUnitTypeName  
            item.Value = obj_UnitType.nUnitTypeID  
            comboBox.Items.Add(item)  
        Next 
    End Sub 
 
 
    Protected Sub RadGrid1_DeleteCommand(ByVal source As ObjectByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.DeleteCommand  
        Try 
            '**********************************************************************************  
            ' extract the grid item from the event args  
            '**********************************************************************************  
            Dim objGridDataItem As GridDataItem = DirectCast(e.Item, GridDataItem)  
            Dim bResult As Boolean 
 
            '**********************************************************************************  
            ' extract the ID from the grid item and perform the delete  
            '**********************************************************************************  
            Dim obj_TradeType As New cls_TradeType()  
 
            obj_TradeType.nTradeTypeID = Convert.ToInt32(objGridDataItem.OwnerTableView.DataKeyValues(objGridDataItem.ItemIndex)("nTradeTypeID").ToString())  
            obj_TradeType.bConcurrencyId = Convert.FromBase64String(CType(e.Item.FindControl("lbConcurrencyId"), Label).Text)  
 
            bResult = obj_TradeType.TradeTypeDelete()  
 
            If bResult = False Then 
                '**********************************************************************************  
                ' set up the ajax manager and display message  
                '**********************************************************************************  
                Dim obj_radAjaxManager As New RadAjaxManager  
                obj_radAjaxManager = RadAjaxManager.GetCurrent(Me.Page)  
                obj_radAjaxManager.Alert("Delete Failed. Please try again")  
            End If 
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 
 
 
 
    Protected Sub RadGrid1_UpdateCommand(ByVal source As ObjectByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.UpdateCommand  
        Try 
            '**********************************************************************************  
            ' extract the grid item and ID from the event args  
            '**********************************************************************************  
            Dim objEditedGridItem As GridEditableItem = DirectCast(e.Item, GridEditableItem)  
            Dim bResult As Boolean 
 
            '**********************************************************************************  
            ' unpack the hash table values into the object and perform the update  
            '**********************************************************************************  
            Dim obj_TradeType As New cls_TradeType()  
 
            obj_TradeType.nTradeTypeID = objEditedGridItem.OwnerTableView.DataKeyValues(objEditedGridItem.ItemIndex)("nTradeTypeID").ToString()  
            obj_TradeType.sTradeTypeName = (TryCast(objEditedGridItem("sTradeTypeName").Controls(0), TextBox)).Text  
            obj_TradeType.mUnitCost = CDec(TryCast(objEditedGridItem("mUnitCost").Controls(0), TextBox).Text)  
 
 
            obj_TradeType.nUnitTypeID = CInt(TryCast(objEditedGridItem("UnitType").Controls(1), RadComboBox).SelectedValue)  
 
            'obj_TradeType.nUnitTypeID = CInt(TryCast(objEditedGridItem("UnitTypeRadComboBox").Controls(0), RadComboBox).SelectedValue)  
            obj_TradeType.mAmount = CDec(TryCast(objEditedGridItem("mAmount").Controls(0), TextBox).Text)  
            obj_TradeType.bConcurrencyId = Convert.FromBase64String(CType(e.Item.FindControl("tbConcurrencyId"), TextBox).Text)  
 
            bResult = obj_TradeType.TradeTypeUpdate()  
 
            If bResult = False Then 
                '**********************************************************************************  
                ' set up the ajax manager and display message  
                '**********************************************************************************  
                Dim obj_radAjaxManager As New RadAjaxManager  
                obj_radAjaxManager = RadAjaxManager.GetCurrent(Me.Page)  
                obj_radAjaxManager.Alert("Update Failed. Please re edit the record and try again")  
            End If 
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 
 
 
 
    Protected Sub RadGrid1_InsertCommand(ByVal source As ObjectByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.InsertCommand  
        Try 
            If Not Page.IsValid Then 
                e.Canceled = True 
            Else 
                '**********************************************************************************  
                ' extract the grid item and ID from the event args  
                '**********************************************************************************  
                Dim objGridDataInsertItem As GridDataInsertItem = DirectCast(e.Item, GridDataInsertItem)  
                Dim bResult As Boolean 
 
                '**********************************************************************************  
                ' unpack the hash table values into the object and perform the insert  
                '**********************************************************************************  
                Dim obj_TradeType As New cls_TradeType()  
 
                obj_TradeType.sTradeTypeName = (TryCast(objGridDataInsertItem("sTradeTypeName").Controls(0), TextBox)).Text  
                obj_TradeType.mUnitCost = CDec(TryCast(objGridDataInsertItem("mUnitCost").Controls(0), TextBox).Text)  
                obj_TradeType.nUnitTypeID = CInt(TryCast(objGridDataInsertItem("UnitTypeRadComboBox").Controls(0), RadComboBox).SelectedValue)  
                obj_TradeType.mAmount = CDec(TryCast(objGridDataInsertItem("mAmount").Controls(0), TextBox).Text)  
                bResult = obj_TradeType.TradeTypeInsert()  
 
                If bResult = False Then 
                    '**********************************************************************************  
                    ' set up the ajax manager and display message  
                    '**********************************************************************************  
                    Dim obj_radAjaxManager As New RadAjaxManager  
                    obj_radAjaxManager = RadAjaxManager.GetCurrent(Me.Page)  
                    obj_radAjaxManager.Alert("Insert Failed. Please try again")  
                End If 
            End If 
 
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 
 
 
 
    Private Sub RadGrid1_ItemCreated(ByVal sender As ObjectByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated  
        If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then 
            Dim item As GridEditableItem = CType(e.Item, GridEditableItem)  
 
            '**********************************************************************************  
            ' Add a required field validator for TradeTypeName  
            '**********************************************************************************  
            Dim objGridTextBoxColumnEditor1 As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("sTradeTypeName"), GridTextBoxColumnEditor)  
            Dim objTableCell1 As TableCell = CType(objGridTextBoxColumnEditor1.TextBoxControl.Parent, TableCell)  
            Dim objRequiredFieldValidator1 As RequiredFieldValidator = New RequiredFieldValidator  
 
            objGridTextBoxColumnEditor1.TextBoxControl.ID = "TradeTypeName_validation" 
            objRequiredFieldValidator1.ControlToValidate = objGridTextBoxColumnEditor1.TextBoxControl.ID  
            objRequiredFieldValidator1.ErrorMessage = "Trade Group Name is Required" 
            objTableCell1.Controls.Add(objRequiredFieldValidator1)  
        End If 
    End Sub 
 
 
    Protected Sub RadGrid1_ItemCommand(ByVal sender As ObjectByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand  
 
        If e.CommandName = RadGrid.InitInsertCommandName Then 
            e.Canceled = True 
            Dim obj_TradeType As New cls_TradeType()  
            e.Item.OwnerTableView.InsertItem(obj_TradeType)  
 
        End If 
    End Sub 
 
 
End Class 

 

 

 

 

 

PROBLEM: This approach seems to work fine right up to the point where I save the selected value.  Unfortunately the OnLoad event fires before the update event and I lose a handle on the selected value, so all saved records end up with the id of the first item in the list 

QUESTION: how do I prevent the onload event from firing when I hit the update button?, or how to I catch the slected value before the onload event fires?


Approach # 2 Load On Demand

html as above except for the following changes to the EditItemTemplate

 

 

 

 

<telerik:RadComboBox DataTextField="sUnitTypeName"   
 DataValueField="nUnitTypeId"   
 OnItemsRequested="UnitTypeRadComboBox_ItemsRequested"   
 EnableLoadOnDemand="True"   
 ID="UnitTypeRadComboBox"   
 SelectedValue='<%#DataBinder.Eval(Container.DataItem, "nUnitTypeId")%>'   
 runat="server"   
 Height="140px"   
 Width="220px" >   
</telerik:RadComboBox> 


PROBLEM: The combobox is not getting populated until the user clicks the dropdown list after the edit row is opened, which means that the SelectedValue='<%#DataBinder.Eval(Container.DataItem, "nUnitTypeId")%>' fails as there are no items in the list.  If I take the SelectedValue='<%#DataBinder.Eval(Container.DataItem, "nUnitTypeId")%>' assignment out of the definition ther update works but I am unable to see the currently selected item when I enter edit mode.

QUESTION: can the OnItemsRequested="UnitTypeRadComboBox_ItemsRequested" method be called when the edit item is opened? or what is the best way to get this simple requirement to work????

 

 

 

 

regards
Mark

 

 

 

 

2 Answers, 1 is accepted

Sort by
0
mark
Top achievements
Rank 1
answered on 25 Aug 2009, 03:40 AM
hello All,

I finally discovered a solution to my requirement.  I decided to avoid the lazy loading of "LoadOnDemand" or the "onLoad" approach.  I modified the markup to the following for the EditItemTemplate.

<telerik:GridTemplateColumn UniqueName="UnitType" HeaderText="Unit Type" 
                        SortExpression="nUnitTypeId">  
                        <FooterTemplate>Template footer</FooterTemplate> 
                        <FooterStyle VerticalAlign="Middle" HorizontalAlign="Center" /> 
                        <ItemTemplate> 
                            <%#DataBinder.Eval(Container.DataItem, "sUnitTypeName")%> 
                        </ItemTemplate> 
                        <EditItemTemplate> 
                            <telerik:RadComboBox DataTextField="sUnitTypeName"   
                                DataValueField="nUnitTypeId" 
                                SelectedValue='<%#DataBinder.Eval(Container.DataItem, "nUnitTypeId")%>' 
                                EnableLoadOnDemand="False" 
                                ID="UnitTypeRadComboBox"   
                                runat="server"   
                                Height="140px"   
                                Width="220px" > 
                            </telerik:RadComboBox> 
                        </EditItemTemplate> 
                    </telerik:GridTemplateColumn> 


I then used the Grid.OnItemCreated event to trap the point to load the combobox as follows:

 Private Sub RadGrid1_ItemCreated(ByVal sender As ObjectByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated  
        Try 
            If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then 
                Dim item As GridEditableItem = CType(e.Item, GridEditableItem)  
 
                '**********************************************************************************  
                ' populate the unit type dropdown list  
                '  
                ' extract the grid item and ID from the event args  
                '**********************************************************************************  
                'Dim objComboBox As RadComboBox = DirectCast(item("UnitType").Controls(1), RadComboBox)  
                Dim objComboBox As RadComboBox = TryCast(item.FindControl("UnitTypeRadComboBox"), RadComboBox)  
 
                '**********************************************************************  
                ' select all the unit types  
                '**********************************************************************  
                Dim obj_UnitTypeCollection As New cls_UnitTypeCollection()  
                obj_UnitTypeCollection = obj_UnitTypeCollection.UnitTypeSelectAll()  
                objComboBox.Items.Clear()  
 
                For Each obj_UnitType As cls_UnitType In obj_UnitTypeCollection  
                    Dim objRadComboBoxItem As New RadComboBoxItem()  
                    objRadComboBoxItem.Text = obj_UnitType.sUnitTypeName  
                    objRadComboBoxItem.Value = obj_UnitType.nUnitTypeID  
                    objComboBox.Items.Add(objRadComboBoxItem)  
                Next 
            End If 
        Catch ex As Exception  
            Throw 
        End Try 
    End Sub 

It ain't flash but at least it works.  I am sure that there must be other approaches that work that manage data via business and data layers rather than datasources associated with the form, but I could not find any.  Maybe someone at Telerik could point me in the right direction.

Regards
Mark.
0
Veli
Telerik team
answered on 26 Aug 2009, 02:32 PM
Hello mark,

The approach you have taken is correct. Only, you can also specify the DataSource property of RadComboBox in the ItemCreated event, and call DataBind on the combo to have it automatically bind to data. Here is a help article to get you started:

Databinding Overview

Best wishes,
Veli
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Tags
Grid
Asked by
mark
Top achievements
Rank 1
Answers by
mark
Top achievements
Rank 1
Veli
Telerik team
Share this question
or