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

[Solved] Editing RadGrid with UserControl,Getting Grid values

1 Answer 792 Views
Grid
This is a migrated thread and some comments may be shown as answers.
William Corry
Top achievements
Rank 1
William Corry asked on 15 Apr 2009, 10:24 PM
I am trying to create a webpage that allows the user to edit the values of a record in a usercontrol.  The webpage contains two comboboxes that allowing the user to pick a date and company.  The user must first select a date.  This action allows provides a parameter for the row source for the second combobx which is populated with companies.  When the user selects a company, the first and second comboboxes provide the parameters for a RadGrid which is populated with a the information for a single company.  To minimize the number of clicks the user has to perform, the RadGrid is made to open in Edit Mode, using a UserControl to display the data. In order to fill in the controls on the control with the values that should be edited, the RadGrid PreRender event is used to determine which values are in being passed to the Grid.  These values are stored in session variables named after the field that held them.  After the values have been stored the datagriditem containing it is placed in edit mode and the grid is rebound. After the rebind command the grid opens in Edit mode displaying the UserControl. The UserGrid controls are populated with the correct values during the RadGrid_ItemDataBound event using the values stored in the session variables.  I have not bound the controls on the usercontrol to the underlying as some of the controls will be multiselect listboxes which cannot be populated this way.

On the selection of the first company the UserForm is properly displayed in edit mode and the controls are properly filled out.  If a second company is selected while the first one is still in edit mode the datasource for the grad grid is properly updated with the data from the second company but the data from the first company is shown in the UserControl.  Upon selecting the second company the datasource for the RadGrid exhibited the selected event, the webpage went through the load event but the RadGrid did not go through the ItemDataBound event before the the RadGrid Prerender event happened.  Because the ItemDataBound event did not occur before the RadGrid_PreRender event the new values for the RadGrid were not entered into the session variables. Therefore the session variables held the values from the first company and these were entered into the UserControl on the RadGrid_PreRender event. 

Can you suggest a fix to this?  I've tried to get the values from the GridEditFormItem using the ExtractValues method but this doesn't work with a UserControl.  Is it possible to force the ItemDataBound event before the RadGrid_PreRender event so that the values can be?  In order to diagnose the problem I placed debug.print statements throughout the code.  The sequence of statements is  shown below:

--User clicks command to open webpage

Page_LoadComplete Event

--Page has just opened; only date control shows

--next is triggered by selecting date

Page PreInit on postback

Page_LoadComplete Event

--on postback control showing companies shows up

--next step is to select ala Mobile

Page PreInit on postback

cboActiveCompanies_SelectedIndexChanged event occurs Selected value = 100576

Load Complete

dsGetSinglePortfolioCompanyCashFlowInfo_Selecting event running for inst_id 100576

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid1_ItemDataBound is GridEditFormItem in EditMode

RadGrid1_ItemDataBound item is not GridEditFormItem

MasterGrid prerender event with Item Count>0 and shouldedit = True

RadGrid PreRender Edit was just set to true - Rebind cmd is next

dsGetSinglePortfolioCompanyCashFlowInfo_Selecting event running for inst_id 100576

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid1_ItemDataBound is GridEditFormItem in EditMode

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid PreRender Edit: Session(Inst_id) set to 100576

RadGrid PreRender Edit: Session(RptDate) set to 12/31/2008 12:00:00 AM

RadGrid PreRender Edit: Session(CompanyNameCurrent) set to a La Mobile, Inc.

---At this point the form shows ala Mobile in the edit form as it should

---The next step is to select select a new company 2Wire

Page PreInit on postback

cboActiveCompanies_SelectedIndexChanged event occurs Selected value = 11880

Page_LoadComplete Event

MasterGrid prerender event with Item Count>0 and shouldedit = True

--This is the point where the RadGrid_ItemDataBound Event should occur but doesn't; any way to force it here?
RadGrid PreRender Edit: Session(Inst_id) set to 100576

RadGrid PreRender Edit: Session(RptDate) set to 12/31/2008 12:00:00 AM

RadGrid PreRender Edit: Session(CompanyNameCurrent) set to a La Mobile, Inc.

RadGrid PreRender Edit was just set to true - Rebind cmd is next

dsGetSinglePortfolioCompanyCashFlowInfo_Selecting event running for inst_id 11880

RadGrid1_ItemDataBound item is not GridEditFormItem

RadGrid1_ItemDataBound item is not GridEditFormItem

UserControl_databinding event

RadGrid1_ItemDataBound is GridEditFormItem in EditMode

RadGrid1_ItemDataBound Updating control for CompanyNameCurrent

RadGrid1_ItemDataBound item is not GridEditFormItem

The following shows the source code for the webpage :

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="CompanyValuationInfo.aspx.vb" Inherits="CompanyValuationInfo" %>  
 
<%@ Register src="AllTab115Instances.ascx" tagname="AllTab115Instances" tagprefix="uc1" %>  
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>  
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Company Valuation</title>  
    <script type="text/javascript">  
      
      function pageLoad() {  
      }  
      
    </script>  
    <style type="text/css">  
        .style1  
        {  
            width: 100%;  
        }  
        .style2  
        {  
            width: 349px;  
        }  
        .style3  
        {  
            width: 562px;  
        }  
        .style4  
        {  
            width: 609px;  
        }  
    </style>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <telerik:RadScriptManager ID="ScriptManager1" runat="server"   
        EnableTheming="True">  
    </telerik:RadScriptManager>  
    <div>  
        <asp:SqlDataSource ID="dsActiveCompanies" runat="server"   
            ConnectionString="<%$ ConnectionStrings:ActiveString %>"   
            SelectCommand="stdprc_GetFinanciallyActivePortfolioCompanies"   
            SelectCommandType="StoredProcedure">  
            <SelectParameters>  
                <asp:ControlParameter ControlID="AllTab115Instances1" DefaultValue="1/1/1900"   
                    Name="AsOfDate" PropertyName="DateValue" Type="DateTime" />  
            </SelectParameters>  
        </asp:SqlDataSource>  
    </div>  
    <table class="style1">  
        <tr>  
            <td class="style2">  
                Select Reporting Date</td>  
            <td class="style4">  
                <uc1:AllTab115Instances ID="AllTab115Instances1" runat="server"   
                    NotBeforeDate="1/1/2004" />  
            </td>  
            <td class="style3">  
                <asp:Label ID="lblSelectCompanyToEdit" runat="server"   
                    Text="Select Company To Edit" Visible="False"></asp:Label>  
            </td>  
            <td>  
                <telerik:RadComboBox ID="cboActiveCompanies" Runat="server"   
                    DataSourceID="dsActiveCompanies" DataTextField="CompanyName"   
                    DataValueField="Inst_id" Skin="WebBlue" Visible="False"   
                    AutoPostBack="True">  
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>  
                </telerik:RadComboBox>  
            </td>  
        </tr>  
        </table>  
    <asp:SqlDataSource ID="dsGetSinglePortfolioCompanyCashFlowInfo" runat="server"   
        ConnectionString="<%$ ConnectionStrings:ActiveString %>"   
        SelectCommand="stdprc_GetSinglePortfolioCompanyCashFlowInfo"   
        SelectCommandType="StoredProcedure">  
        <SelectParameters>  
            <asp:ControlParameter ControlID="cboActiveCompanies" Name="Inst_id"   
                PropertyName="SelectedValue" Type="Int32" />  
            <asp:ControlParameter ControlID="AllTab115Instances1" DefaultValue="12/31/1900"   
                Name="RptDate" PropertyName="DateValue" Type="DateTime" />  
        </SelectParameters>  
    </asp:SqlDataSource>  
    <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"   
        DataSourceID="dsGetSinglePortfolioCompanyCashFlowInfo" GridLines="None"   
        Skin="WebBlue" Visible="False">  
<HeaderContextMenu>  
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>  
</HeaderContextMenu>  
 
<MasterTableView DataSourceID="dsGetSinglePortfolioCompanyCashFlowInfo"   
            datakeynames="Inst_ID,RptDate">  
<RowIndicatorColumn>  
<HeaderStyle Width="20px"></HeaderStyle>  
</RowIndicatorColumn>  
 
<ExpandCollapseColumn>  
<HeaderStyle Width="20px"></HeaderStyle>  
</ExpandCollapseColumn>  
    <Columns>  
        <telerik:GridBoundColumn DataField="Inst_id" DataType="System.Int32"   
            HeaderAbbr="Inst_id" ReadOnly="True" UniqueName="Inst_id">  
        </telerik:GridBoundColumn>  
        <telerik:GridBoundColumn DataField="RptDate" ReadOnly="True"   
            UniqueName="RptDate">  
        </telerik:GridBoundColumn>  
        <telerik:GridBoundColumn DataField="CompanyNameCurrent"   
            UniqueName="CompanyNameCurrent">  
        </telerik:GridBoundColumn>  
    </Columns>  
    <EditFormSettings EditFormType="WebUserControl"   
        UserControlName="CashFlowFields.ascx">  
    </EditFormSettings>  
</MasterTableView>  
 
<FilterMenu>  
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>  
</FilterMenu>  
    </telerik:RadGrid>  
    </form>  
<p>  
    &nbsp;</p>  
</body>  
</html>  
 
This is the aspx.vb code that goes with the web page:
Imports Telerik.Web.UI  
Imports VenRockClassLibrary  
Imports System.Diagnostics  
Partial Class CompanyValuationInfo  
    Inherits System.Web.UI.Page  
 
    Protected Sub Page_LoadComplete(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.LoadComplete  
        System.Diagnostics.Debug.WriteLine("Page_LoadComplete Event")  
    End Sub 
 
    Protected Sub Page_PreInit(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.PreInit  
        Dim Pg As Page = CType(sender, Page)  
        If Pg.IsPostBack Then                   'Always do this as Date combobox has been pressed at least once  
            Me.cboActiveCompanies.Visible = True 
            Me.lblSelectCompanyToEdit.Visible = True 
            System.Diagnostics.Debug.WriteLine("Page PreInit on postback")  
        End If 
    End Sub 
 
    Protected Sub cboActiveCompanies_SelectedIndexChanged(ByVal o As ObjectByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs) Handles cboActiveCompanies.SelectedIndexChanged  
        Session("AsOfDate") = Me.AllTab115Instances1.DateValue  
        'after user selects a company then make the company visible  
        RadGrid1.Visible = True 
 
        If cboActiveCompanies.SelectedIndex = -1 Then 
            System.Diagnostics.Debug.WriteLine("cboActiveCompanies_SelectedIndexChanged event occurs Selected index = -1")  
            Session("ShouldEdit") = False 
        Else 
            System.Diagnostics.Debug.WriteLine("cboActiveCompanies_SelectedIndexChanged event occurs Selected value = " & cboActiveCompanies.SelectedValue)  
            Session("ShouldEdit") = True 
        End If 
    End Sub 
 
 
 
    Protected Sub RadGrid1_ItemDataBound(ByVal sender As ObjectByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound  
 
        If (TypeOf e.Item Is GridEditFormItem) Then 
            If e.Item.IsInEditMode Then 
                System.Diagnostics.Debug.WriteLine("RadGrid1_ItemDataBound is GridEditFormItem in EditMode")  
                Dim ctl As Control, ctl_ID As String 
 
 
                Dim usrCtl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)  
                'the next code block works because the controls are named after the fields in the stored procedures  
                'For example there is a control named Inst_id to refect the value of the Inst_ID field  
                For Each ctl In usrCtl.Controls  
                    Try 
                        ctl_ID = ctl.ID  
                        If Len(Session(ctl_ID)) > 0 Then 
                            System.Diagnostics.Debug.WriteLine("RadGrid1_ItemDataBound Updating control for " & ctl_ID)  
                            UpdateControlValue(ctl, Session(ctl_ID))  
                        End If 
                    Catch ex As Exception  
                        System.Windows.Forms.MessageBox.Show(ex.ToString)  
                    End Try 
                Next 
            Else 
                System.Diagnostics.Debug.WriteLine("RadGrid1_ItemDataBound is GridEditFormItem in EditMode")  
            End If 
        Else 
            System.Diagnostics.Debug.WriteLine("RadGrid1_ItemDataBound item is not GridEditFormItem")  
        End If 
    End Sub 
    Protected Sub UpdateControlValue(ByVal ctl As Web.UI.Control, ByVal Value As String)  
        'sub will ensure that the controls used to display the value of the various fields  
        'have the old value of the field displayed  
        Select Case True 
            Case TypeOf (ctl) Is RadTextBox  
                Dim nCtl As RadTextBox = CType(ctl, RadTextBox)  
                nCtl.Text = Value  
            Case TypeOf ctl Is RadComboBox  
                Dim nCtl As RadComboBox = CType(ctl, RadComboBox)  
                nCtl.SelectedValue = Value  
            Case TypeOf ctl Is ListBox  
                Dim nCtl As ListBox = CType(ctl, ListBox)  
                VRUtilities.SetMultipleItemsSelection(nCtl, Value)  
        End Select 
 
    End Sub 
 
    Protected Sub RadGrid1_PreRender(ByVal sender As ObjectByVal e As System.EventArgs) Handles RadGrid1.PreRender  
        Dim ShouldEdit As Boolean 
        'set a switch so that the items is only marked if the session variable is set to true  
        'this only happens when the SelectedIndex of cboActiveCompanies > -1  
        'it can also be undone by the cancel button  
        If Session("ShouldEdit") = True Then 
            ShouldEdit = True 
        Else 
            ShouldEdit = False 
        End If 
        'procedure places each value into a session variable which are then used used to populate  
        'the vallues   
        'if it is a postback and an active company has been selected  
        If RadGrid1.MasterTableView.Items.Count > 0 Then 
            If ShouldEdit Then 
                System.Diagnostics.Debug.WriteLine("MasterGrid prerender event with Item Count>0 and shouldedit = True")  
                Dim colCnt As Int16, ColNames As String(), j As Int16, GC As GridColumn, ColName As String 
                Dim TCell As TableCell, sText As String 
 
                Dim RG As RadGrid = CType(sender, RadGrid)  
 
                'RG.MasterTableView.Items(0).Edit = True  
                'System.Diagnostics.Debug.WriteLine("RadGrid PreRender Edit was just set to true - Rebind cmd is next")  
                'RG.Rebind()  
 
                Dim DGI As GridDataItem = RG.MasterTableView.Items(0)  
                'got through all of the columns find the control and save the value to   
                'a session variable  
                colCnt = RG.Columns.Count  
                ReDim ColNames(colCnt - 1)  
 
                For j = 0 To colCnt - 1  
                    GC = RG.Columns(j)          'get the Jth column  
                    ColName = GC.UniqueName     'get the unique name for the column  
                    ColNames(j) = ColName  
                    If ColName <> "EditCommandColumn" Then 
                        TCell = CType(DGI.Item(ColName), TableCell)    'get the tablecell for this column  
                        sText = TCell.Text  
                        sText = Replace(sText, "&nbsp;""")  
                        System.Diagnostics.Debug.WriteLine("RadGrid PreRender Edit: Session(" & ColName & ") set to " & sText)  
                        Session(ColName) = sText       'store the text in the cell as a session variable  
                    End If 
                Next j  
 
                RG.MasterTableView.Items(0).Edit = True 
                System.Diagnostics.Debug.WriteLine("RadGrid PreRender Edit was just set to true - Rebind cmd is next")  
                RG.Rebind()  
            Else 
                System.Diagnostics.Debug.WriteLine("MasterGrid prerender event with Item Count>0 and shouldedit = false")  
            End If 
        Else 
            System.Diagnostics.Debug.WriteLine("RadGrid PreRender with item count 0")  
        End If 
    End Sub 
 
    Protected Sub dsGetSinglePortfolioCompanyCashFlowInfo_Selected(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsGetSinglePortfolioCompanyCashFlowInfo.Selected  
        'System.Diagnostics.Debug.WriteLine("dsGetSinglePortfolioCompanyCashFlowInfo_Selected event finished.")  
    End Sub 
 
 
    Protected Sub dsGetSinglePortfolioCompanyCashFlowInfo_Selecting(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles dsGetSinglePortfolioCompanyCashFlowInfo.Selecting  
 
        'Dim SDSV As SqlDataSourceView = CType(sender, SqlDataSourceView)  
        'If SDSV.SelectCommand = "stdprc_GetSinglePortfolioCompanyCashFlowInfo" Then  
        '    Dim parm1 As Parameter = SDSV.SelectParameters.Item(0)  
        '    Dim parm2 As Parameter = SDSV.SelectParameters.Item(1)  
        'End If  
        Dim Cmd As System.Data.Common.DbCommand = CType(e.Command, System.Data.Common.DbCommand)  
        Dim parm1 As System.Data.Common.DbParameter = Cmd.Parameters(0)  
        Dim parm2 As System.Data.Common.DbParameter = Cmd.Parameters(1)  
        System.Diagnostics.Debug.WriteLine("dsGetSinglePortfolioCompanyCashFlowInfo_Selecting event running for inst_id " & parm1.Value)  
    End Sub 
End Class 
 

This is the souce code for the UserControl:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CashFlowFields.ascx.vb" Inherits="CashFlowFields" %>  
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>  
<style type="text/css">  
    .style1  
    {  
        width: 100%;  
    }  
</style>  
<table class="style1">  
    <tr>  
        <td>  
            <asp:Button ID="cmdUpdate" runat="server" Text="Update" />  
        </td>  
        <td>  
            <asp:Button ID="cmdCancel" runat="server" Text="Cancel" />  
        </td>  
    </tr>  
    <tr>  
        <td>  
            &nbsp;</td>  
        <td>  
            &nbsp;</td>  
    </tr>  
</table>  
<telerik:RadTextBox ID="CompanyNameCurrent" Runat="server" Height="20px"   
    Skin="WebBlue" Width="311px">  
</telerik:RadTextBox>  
 
This is the aspx.vb code that goes with the UserControl.
Imports VRUtilities  
Imports Telerik.Web.UI  
Partial Class CashFlowFields  
    Inherits System.Web.UI.UserControl  
    Private Shared m_DataItem As Object = Nothing 
    Protected Sub cmdUpdate_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles cmdUpdate.Click  
        Dim btn As Button = CType(sender, Button)  
        Dim usrCtl As UserControl = CType(btn.Parent, ASP.cashflowfields_ascx)  
        Dim ctl As Control, ctl_id As String, PriorVal As String, CurrVal As String 
        For Each ctl In usrCtl.Controls  
            If Not TypeOf ctl Is Button And Not TypeOf ctl Is LiteralControl Then 
                ctl_id = ctl.ID  
                PriorVal = Session(ctl_id)  
                CurrVal = VRUtilities.GetControlsValue(ctl)  
                If CurrVal <> PriorVal Then 
                    MsgBox("New values for " & ctl_id & " change from " & PriorVal & " to " & CurrVal)  
                Else 
                    MsgBox("Same values for " & ctl_id & " as " & PriorVal & " = " & CurrVal)  
                End If 
            End If 
        Next 
    End Sub 
    Protected Sub cmdCancel_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles cmdCancel.Click  
 
        CancelEditView()  
 
 
    End Sub 
    Protected Sub CancelEditView()  
 
        Try 
            Dim RG As Telerik.Web.UI.RadGrid = CType(Me.Page.FindControl("RadGrid1"), Telerik.Web.UI.RadGrid)  
            Dim GTV As Telerik.Web.UI.GridTableView = CType(RG.MasterTableView, Telerik.Web.UI.GridTableView)  
            GTV.ClearEditItems()  
 
            'Dim cBx As RadComboBox = CType(Me.Page.FindControl("cboActiveCompanies"), RadComboBox)  
            'cBx.SelectedIndex = -1  
            Session("ShouldEdit") = False 
            System.Diagnostics.Debug.WriteLine("cmdCancel_Click event has set System(shouldedit) to false")  
        Catch ex As Exception  
            System.Windows.Forms.MessageBox.Show(ex.ToString)  
        End Try 
 
    End Sub 
 
    Public Shared Property DataItem() As Object 
        Get 
            Return m_DataItem  
        End Get 
        Set(ByVal value As Object)  
            m_DataItem = value  
        End Set 
    End Property 
 
    Protected Sub Page_DataBinding(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.DataBinding  
        System.Diagnostics.Debug.WriteLine("UserControl_databinding event ")  
    End Sub 
End Class 
 

So if you're still with me, my problem is how can I populate the usercontrol with the values returned by the datasource for the radgrad. I also need to keep track of the values placed in the usercontrol controls as when the Update command is triggered I only want to update the record if the values were changed.

Thanks,  I'm three days into this and it seems intractable at the moment.

1 Answer, 1 is accepted

Sort by
0
Georgi Krustev
Telerik team
answered on 22 Apr 2009, 10:24 AM
Hello William,

I reviewed the provided detailed explanation of the problem and in point of view, I think that your user control need to implement the IBindableControl interface in order to achieve your goal. Please examine the following help article (bottom of it) devoted on this matter:
http://www.telerik.com/help/aspnet-ajax/grdupdatingvaluesusercontrolformtemplate.html

For further information how to populate the user control with data from the Grid's data source please review these online help topics:
http://www.telerik.com/help/aspnet-ajax/grdcustomeditforms.html
http://www.telerik.com/help/aspnet-ajax/grdupdatingvaluesusercontrolformtemplate.html

Best regards,
Georgi Krustev
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Tags
Grid
Asked by
William Corry
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Share this question
or