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

Get reference to usercontrol in grid template

14 Answers 576 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Nigel
Top achievements
Rank 1
Nigel asked on 17 Jul 2008, 02:28 PM
Hi

I have a main usercontrol that has a RadGrid on it, within a template column of the grid I have another usercontrol (ProductSelect.ascx which displays several check boxes for the user to select options).

How do I get a reference to the ProductSelect UC so that I can access it's properties and methods?

Tried various things but nothing seems to work.

Thanks

14 Answers, 1 is accepted

Sort by
0
Veli
Telerik team
answered on 18 Jul 2008, 01:13 PM
Hi Nigel,

Could you, please specify how do you initialize your custom user control on the page and how do you define your
RadGrid inside the user control. If you declaratively add the user control to the page, and also declaratively place a Radgrid in the user control, you should be able to find Radgrid using the UserControlId.FindControl("RadGridID") method.

Regards,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Nigel
Top achievements
Rank 1
answered on 18 Jul 2008, 01:43 PM
Hi Veli

I have just created the main usercontrol form and added the RadGrid by dragging onto the page in design mode and then just dragged the other usercontrol (ProductSelect.ascx) into a template column whilst in edit template mode.

I'm quite a novice at using usercontrols within usercontrols - if I drop the ProductSelect.ascx control outside the template column then I can access it's properties in the code behind with Intellisense - it's when it's within a template column I can't work out how to get the reference - do I need to cast it some how like when doing for standard web controls like

RadComboBox

list = item.FindControl("RadComboVirtualServers") as RadComboBox;

0
Daniel
Top achievements
Rank 1
answered on 18 Jul 2008, 04:22 PM
Hi Nigel And Veli,

I'm also having the same problem. I have my tamplate column and in the item template i have a label that displays a value of the datasource, but in editing mode i need to display an user control that opens a rad window. here is my column code:
<telerik:GridTemplateColumn HeaderText="Name M" 
SortExpression="NameM" UniqueName="NameM"
  EditFormColumnIndex="1">
      <HeaderStyle Width="80px" />
      <ItemTemplate>
           <asp:Label runat="server" ID="lblName"
Text='<%# Eval("Name") %>'>
</asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
           <uc1:TextboxMaster ID="TextboxMaster1" runat="server" />
      </EditItemTemplate>
</telerik:GridTemplateColumn>
The label shows the correct value, but when i enter in editing mode it shows the control, but it didnt works. Also if i add the control outside the grid it works fine, whts the problem??? ....

thanks for your help

 
0
Richard
Top achievements
Rank 1
answered on 21 Jul 2008, 11:03 PM
Nigel,

Casting the control as in your RadComboBox example should work.

Daniel,

Your UserControl needs to expose a property that you can bind to your data field.  For example, if your uc exposes a Text property you would just add

Text='<%# Bind("Name") %>'

Then in the setter of the property within the UserControl you can put that value wherever you need it. 


0
Nigel
Top achievements
Rank 1
answered on 22 Jul 2008, 08:30 AM
Hi Richard

What is the correct syntax if I put

ProductsSelect ps = editedItem.FindControl("ProductsSelect1") as ProductsSelect;

It won't compile and says

Error 1 The type or namespace name 'ProductsSelect' could not be found (are you missing a using directive or an assembly reference?) C:\Sites\LicenceTracker\LicenceTracker.Website\controls\PhysicalSystems.ascx.cs 152 9 C:\...\LicenceTracker.Website\

How do I get it to recognise the ProductsSelect usercontrol think I need to add a reference to it some how. It is registered in the page using 

<%@ Register Src="ProductsSelect.ascx" TagName="ProductsSelect" TagPrefix="uc4" %>

I'm sure it's something really simple!

Cheers

0
Richard
Top achievements
Rank 1
answered on 22 Jul 2008, 02:13 PM
It looks to me like it should work.  I don't use any other references, and though I prefer to use the syntax:

ProductsSelect ps = (ProductsSelect)editedItem.FindControl("ProductsSelect1");

it works either way.  I do get a warning saying 'Can't resolve type or namespace', but it still compiles and runs ok.

It is possible that the problem is due to the usercontrol inside usercontrol scenario, which I haven't really played with.
0
Veli
Telerik team
answered on 22 Jul 2008, 02:52 PM
Hi Guys,

You can find attached a sample project demonstrating both approaches. A custom user control is defined in the project, containing one single TextBox control. We use the custom control inside the EditItemTemplate of a GridTemplateColumn, so that it replaces the column editor.

The first approach is the one suggested by Richard, where the custom control exposes a public property to set the Text of the TextBox inside:

public string Text 
    get 
    { 
        return TextBox1.Text; 
    } 
    set 
    { 
        TextBox1.Text = value; 
    } 

This is used when defining the structure of the EditItemTemplate in the Default.aspx page. You can see that the custom control has a Text property we can bind to:

<EditItemTemplate> 
    <uc:EditControl ID="EditControl1" runat="server" Text='<%# Bind("Description") %>' /> 
</EditItemTemplate> 

The second approach is getting a reference to the custom control in the ItemDataBound event. Please note that we first need to find the custom control, and then the TextBox inside it:

if (e.Item is GridEditFormItem && e.Item.IsInEditMode && e.Item.ItemIndex == 5) 
    GridEditFormItem item = e.Item as GridEditFormItem; 
    (item.FindControl("EditControl1").FindControl("TextBox1"as TextBox).Text = "Text modified in ItemDataBound event"

Essentially, what this code does is modify the Text inside the TextBox of item with index 5 when the item goes in edit mode. And if you run the project, you can observe that all the items in edit mode have their Description field bound to the custom control's textbox text (implemented as the first approach), and only item with CategoryID=6 (ItemIndex = 5) has its Description text modified (due to the code in the ItemDataBound event).

Greetings,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Nigel
Top achievements
Rank 1
answered on 22 Jul 2008, 03:20 PM
Hi

Yes it is to do with the fact it's a usercontrol in a usercontrol. If I add the ProductSelect uc to a .aspx page it works fine.

Veli - thanks for your example but could you do one that uses a usercontrol within a usercontrol?

I am using the tab control to load various usercontrols into the main .aspx page and on most of these I need a radgrid that has the ProductSelect uc in a template column. I currently have got round it by duplicating the code for the ProductSelect uc in each of the grids but that sort of defeats the object of having user controls!

Thanks

Nige
0
Veli
Telerik team
answered on 23 Jul 2008, 12:54 PM
Hi Nigel,

Could you, please, describe how would you access such a user control using MS GridView instead of RadGrid, as I do not seem to understand the problem. How would you do it with the GridView control?

Kind regards,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Nigel
Top achievements
Rank 1
answered on 23 Jul 2008, 01:36 PM
Hi Veli

I suspect I would have the same problem if it were a MS GridView instead of a RadGrid - it's not a problem with RadGrid as such - more a lack of my knowledge!

The problem is not being able to access a usercontrol that is itself in a usercontrol.

here are the 2 .ascx files below

The main usercontrol - PhysicalSystems.ascx and the usercontrol (ProductSelect.ascx) in a edit template of the radgrid

Hope this explains what I am trying to do better!

thanks

<%

@ Control Language="C#" AutoEventWireup="true" CodeFile="PhysicalSystems.ascx.cs" Inherits="controls_PhysicalServers" %>

<%

@ Register Src="ProductsSelect.ascx" TagName="ProductsSelect" TagPrefix="uc4" %>

<%

@ Register Src="ProductsList.ascx" TagName="ProductsList" TagPrefix="uc3" %>

<%

@ Register Src="OperatingSystem.ascx" TagName="OperatingSystem" TagPrefix="uc1" %>

<%

@ Register Src="CPUTypes.ascx" TagName="CPUTypes" TagPrefix="uc2" %>

<%

@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<

telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">

<

script type="text/javascript">

<!--

var hasChanges, inputs, dropdowns, editedRow;

function RowDblClick(sender, eventArgs)

{

if(editedRow && hasChanges)

{

if(confirm("Update changes?"))

{

hasChanges =

false;

$find(

"<%= RadGrid1.MasterTableView.ClientID %>").updateItem(editedRow);

}

else

{

hasChanges =

false;

}

}

editedRow = eventArgs.get_itemIndexHierarchical();

$find(

"<%= RadGrid1.MasterTableView.ClientID %>").editItem(editedRow);

}

function GridCreated(sender, eventArgs)

{

var gridElement = sender.get_element();

var elementsToUse = [];

inputs = gridElement.getElementsByTagName(

"input");

for (var i = 0; i < inputs.length;i++)

{

if(inputs[i].type.toLowerCase() == "hidden")

{

continue;

}

Array.add(elementsToUse, inputs[i]);

inputs[i].onchange = TrackChanges;

}

dropdowns = gridElement.getElementsByTagName(

"select");

for (var i = 0; i < dropdowns.length;i++)

{

dropdowns[i].onchange = TrackChanges;

}

setTimeout(

function(){if(elementsToUse[0])elementsToUse[0].focus();},100);

}

function TrackChanges(e)

{

hasChanges =

true;

}

-->

</script>

</

telerik:RadScriptBlock>

<

telerik:RadGrid ID="RadGrid1" ShowFooter="True" EnableEmbeddedSkins="False" Skin="DefaultSS" runat="server" GridLines="None" AllowSorting="True" AutoGenerateColumns="False" OnNeedDataSource="RadGrid1_NeedDataSource" EnableEmbeddedBaseStylesheet="False" OnItemDataBound="RadGrid1_ItemDataBound" OnUpdateCommand="RadGrid1_UpdateCommand" Height="335px" OnItemCommand="RadGrid1_ItemCommand" >

<MasterTableView CommandItemDisplay="Top" DataKeyNames="AuditDataNodeID" AllowNaturalSort="False" >

<RowIndicatorColumn Visible="False" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<HeaderStyle Width="20px" />

</RowIndicatorColumn>

<ExpandCollapseColumn Resizable="False" Visible="False" CollapseImageUrl="SingleMinus.gif" ExpandImageUrl="SinglePlus.gif" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<HeaderStyle Width="20px" />

</ExpandCollapseColumn>

<EditFormSettings EditFormType="Template">

<PopUpSettings ScrollBars="None" />

<EditColumn CancelImageUrl="Cancel.gif" EditImageUrl="Edit.gif" FilterImageUrl="Filter.gif"

InsertImageUrl="Update.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif"

UpdateImageUrl="Update.gif" UniqueName="EditCommandColumn1">

</EditColumn>

<FormTemplate>

<div id="editForm" style="padding:10px; background-color:ghostwhite">

<table border="0" >

<tr>

<td style="width: 103px">

Host:

</td>

<td >

<asp:TextBox ID="txtHostEdit" runat="server" Text='<%# Bind("Hostname") %>'></asp:TextBox></td>

<td style="width: 112px">

</td>

<td style="width: 112px">

Operating system:

</td>

<td>

<telerik:RadComboBox ID="RadComboOS" runat="server" DataSourceID="AuditOsCacheDataSource1"

Skin="Office2007" DataTextField="AuditOSCacheName" DataValueField="AuditOSCacheName"

SelectedValue='<%# bind("OSCaption") %>' Width="300px" DropDownWidth="350px" >

<CollapseAnimation Duration="200" Type="OutQuint" />

</telerik:RadComboBox>

</td>

</tr>

<tr>

<td style="width: 103px">

Nodes:

</td>

<td style="width: 100px">

<asp:TextBox ID="txtNodesEdit" runat="server" Text='<%# Bind("Nodename") %>' TextMode="MultiLine" Enabled="False"></asp:TextBox></td>

<td style="width: 112px">

</td>

<td style="width: 112px">

CPU type:

</td>

<td style="width: 100px">

<telerik:RadComboBox ID="RadComboCPU" runat="server" AppendDataBoundItems="True"

DataSourceID="AuditCpuTypesDataSource1" DataTextField="SystemProcessorType" DataValueField="SystemProcessorType"

SelectedValue='<%# Bind("SystemProcessorType") %>' Skin="Office2007" Width="300px">

<CollapseAnimation Duration="200" Type="OutQuint" />

</telerik:RadComboBox>

</td>

</tr>

<tr>

<td style="width: 103px" valign="top">

Licence status:

</td>

<td valign="top">

<telerik:RadComboBox ID="RadComboLicenceStatus" runat="server" Skin="Office2007" SelectedValue='<%# Bind("LicenseStatus") %>' AppendDataBoundItems="true">

<CollapseAnimation Duration="200" Type="OutQuint" />

<Items>

<telerik:RadComboBoxItem runat="server" Text="CLUSTER-PASSIVE" Value="CLUSTER-PASSIVE" />

<telerik:RadComboBoxItem runat="server" Text="DECOM" Value="DECOM" />

<telerik:RadComboBoxItem runat="server" Text="DR-PASSIVE" Value="DR-PASSIVE" />

<telerik:RadComboBoxItem runat="server" Text="LIVE" Value="LIVE" />

<telerik:RadComboBoxItem runat="server" Text="OTHER-NON LIVE" Value="OTHER-NON LIVE" />

<telerik:RadComboBoxItem runat="server" Text="TEST" Value="TEST" />

<telerik:RadComboBoxItem runat="server" Text="UNKNOWN" Value="UNKNOWN" />

</Items>

</telerik:RadComboBox>

</td>

<td style="width: 112px" valign="top">

</td>

<td style="width: 112px" valign="top">

Cores:

</td>

<td valign="top">

<asp:TextBox ID="txtCoresEdit" runat="server" Text='<%# Bind("SystemProcessorCount") %>' Width="40px"></asp:TextBox></td>

</tr>

<tr>

<td style="width: 103px" valign="top">

Type

</td>

<td valign="top">

<asp:RadioButtonList ID="rdolstType" runat="server" RepeatDirection="Horizontal">

<asp:ListItem Value="0">Server</asp:ListItem>

<asp:ListItem Selected="True" Value="1">Desktop</asp:ListItem>

</asp:RadioButtonList></td>

<td style="width: 112px" valign="top">

</td>

<td style="width: 112px" valign="top">

Status

</td>

<td valign="top">

<asp:CheckBox ID="chkApproved" runat="server" Text="Approved" TextAlign="Left" Checked="True" /></td>

</tr>

<tr>

<td style="width: 103px" valign="top">

</td>

<td valign="top">

<uc4:ProductsSelect ID="ProductsSelect1" runat="server" />

</td>

<td style="width: 112px" valign="top">

</td>

<td style="width: 112px" valign="top">

</td>

<td valign="top">

</td>

</tr>

</table>

<br />

<asp:LinkButton ID="lnkbtnUpdate" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'

runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'>

</asp:LinkButton>&nbsp;

<

asp:LinkButton ID="lnkbtnCancel" Text="Cancel" runat="server" CausesValidation="False"

CommandName

="Cancel"></asp:LinkButton>

</

div>

 

 

</FormTemplate>

<FormTableStyle BorderColor="Aqua" />

</EditFormSettings>

<Columns>

<telerik:GridEditCommandColumn CancelImageUrl="Cancel.gif" EditImageUrl="Edit.gif"

FilterImageUrl="Filter.gif" InsertImageUrl="Update.gif" SortAscImageUrl="SortAsc.gif"

SortDescImageUrl="SortDesc.gif" UpdateImageUrl="Update.gif">

<ItemStyle Width="50px" VerticalAlign="Top" />

<HeaderStyle Width="50px" />

<FooterStyle Width="50px" />

</telerik:GridEditCommandColumn>

<telerik:GridButtonColumn CommandName="Un-approve" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif"

SortDescImageUrl="SortDesc.gif" Text="Un-approve" UniqueName="ApproveSelect" ButtonType="ImageButton" ConfirmText="Set as un-audited?" ConfirmTitle="Confirm" ImageUrl="../images/28.png" HeaderText="Un-approve" ShowSortIcon="False">

<ItemStyle Width="70px" VerticalAlign="Top" HorizontalAlign="Center" />

<HeaderStyle Width="70px" />

<FooterStyle Width="70px" />

</telerik:GridButtonColumn>

<telerik:GridBoundColumn DataField="Hostname" HeaderText="Host" UniqueName="column1" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<ItemStyle Width="100px" HorizontalAlign="Left" VerticalAlign="Top" />

<HeaderStyle Width="100px" />

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="Nodename" HeaderText="Node names" UniqueName="column21" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<ItemStyle Width="100px" HorizontalAlign="Left" VerticalAlign="Top" />

<HeaderStyle Width="100px" />

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="LicenseStatus" HeaderText="Licence Status" UniqueName="LicenceStatus" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" Width="150px" />

<FooterStyle Font-Bold="True" />

<HeaderStyle Width="150px" />

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="OSCaption" HeaderText="Operating System" UniqueName="column2" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="SystemProcessorType" HeaderText="CPU Type" UniqueName="column4" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="SystemProcessorCount" HeaderText="Number CPU Cores"

UniqueName="column7" FilterImageUrl="Filter.gif" SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif" Aggregate="Sum" FooterAggregateFormatString="Total cores: {0}" >

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />

<FooterStyle Font-Bold="True" />

<HeaderStyle Width="100px" />

</telerik:GridBoundColumn>

<telerik:GridTemplateColumn FilterImageUrl="Filter.gif" HeaderText="Products" SortAscImageUrl="SortAsc.gif"

SortDescImageUrl="SortDesc.gif" UniqueName="TemplateColumn">

<ItemTemplate>

<uc3:ProductsList ID="ProductsList1" AuditDataGuid='<%# AuditGuid %>' AuditDataNodeGUID='<%# Bind("AuditDataNodeGUID") %>' runat="server" />

</ItemTemplate>

</telerik:GridTemplateColumn>

</Columns>

<CommandItemSettings AddNewRecordImageUrl="AddRecord.gif" RefreshImageUrl="Refresh.gif" />

<PagerStyle FirstPageImageUrl="PagingFirst.gif" LastPageImageUrl="PagingLast.gif"

NextPageImageUrl="PagingNext.gif" PrevPageImageUrl="PagingPrev.gif" />

</MasterTableView>

<ClientSettings>

<Scrolling AllowScroll="True" UseStaticHeaders="True" FrozenColumnsCount="1" />

<ClientEvents OnRowDblClick="RowDblClick" />

<Selecting AllowRowSelect="True" />

</ClientSettings>

<PagerStyle FirstPageImageUrl="PagingFirst.gif" LastPageImageUrl="PagingLast.gif"

NextPageImageUrl="PagingNext.gif" PrevPageImageUrl="PagingPrev.gif" />

</

telerik:RadGrid>

 

<

data:AuditOsCacheDataSource ID="AuditOsCacheDataSource1" runat="server" CacheDuration="120" SelectMethod="GetAll" EnableCaching="True">

<DeepLoadProperties Method="IncludeChildren" Recursive="False">

</DeepLoadProperties>

</

data:AuditOsCacheDataSource>

<

data:AuditCpuTypesDataSource ID="AuditCpuTypesDataSource1" runat="server" CacheDuration="120" SelectMethod="GetAll" EnableCaching="True">

<DeepLoadProperties Method="IncludeChildren" Recursive="False">

</DeepLoadProperties>

</

data:AuditCpuTypesDataSource>


<%

@ Control Language="C#" AutoEventWireup="true" CodeFile="ProductsSelect.ascx.cs"

Inherits="controls_ProductsSelect" %>

<

asp:Repeater ID="rptProductSelect" runat="server" OnItemDataBound="rptProductSelect_ItemDataBound">

<HeaderTemplate>

<ul class="productsList">

</HeaderTemplate>

<ItemTemplate>

<li>

<asp:CheckBox ID="chkbx" EnableViewState="true" Text='<%# DataBinder.Eval(Container.DataItem, "AuditTSMProductName")%>'

runat="server" />

</li>

</ItemTemplate>

<FooterTemplate>

</ul>

</FooterTemplate>

</

asp:Repeater>

0
Richard
Top achievements
Rank 1
answered on 23 Jul 2008, 02:45 PM
Hi Nigel,

I haven't tested this out, but the only way I can think of to make this work would be to put a property on your main usercontrol that exposes the inner grid (or part of it) in some way.

Maybe something like - in your PhysicalSystems.ascx - add

private ProductSelect _currentUC = null;

public ProductSelect CurrentProductSelect
{
      get{ return _currentUC; }
}

private RadGrid1_ItemCreated (object sender, GridItemEventArgs e)
{
      if (e.Item.IsInEditMode)
      {
            _currentUC = e.item.FindControl("ProductsSelect1");
      }
}

... and then in the UpdateCommand and CancelCommand you would have to set the _currentUC back to null.   I'm not certain that it would work exactly as written, but that is the approach that I would try.
0
Richard
Top achievements
Rank 1
answered on 23 Jul 2008, 02:46 PM
(duplicate post)
0
Accepted
Veli
Telerik team
answered on 24 Jul 2008, 08:29 AM
Hi Guys,

Richard, you are right in your supposition, your custom control needs to expose its RadGrid object or part of it, so that we can reference it in the container page. The reason for this is that the edit form items need to be modified before rendering in the ItemDataBound event of RadGrid. To reference the event, we need a RadGrid object reference, so that we can define an event handler inside the page code-behind. After that, we  can find the second user control in the edit form and the controls inside to set their properties.

All this is demonstrated in the attached sample project.

Kind regards,
Veli
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Nigel
Top achievements
Rank 1
answered on 24 Jul 2008, 08:54 AM
Hi Guys

Thanks for all your help - not implemented it yet but looks like this is the solution.

Thanks again

Cheers

Nige
Tags
Grid
Asked by
Nigel
Top achievements
Rank 1
Answers by
Veli
Telerik team
Nigel
Top achievements
Rank 1
Daniel
Top achievements
Rank 1
Richard
Top achievements
Rank 1
Share this question
or