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

Delete a Row from RadGrid Client-Side

4 Answers 1055 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jonathan
Top achievements
Rank 1
Jonathan asked on 14 Feb 2012, 04:39 PM
Hi

I am having a problem at the moment removing a row from the RadGrid client side.

Our RadGrid is built up via xml defined from a generic RadGrid declaration. On the particular page i am trying to remove a row i have the following defined (where index is the row selected):

function DeleteRow(index)
{
     var masterTable = $find('<%=RadGrid1.ClientID=>').get_masterTableView();
     masterTable.deleteItem(masterTable.get_dataItems()[index].get_element());
}

The problem is that function deletes all rows in my grid and not the index that i supplied it. I have checked the index value and can confirm that changes to the row i have clicked on. Can you provide an alternative solution?

Regards,
Jonathan

4 Answers, 1 is accepted

Sort by
0
Tsvetoslav
Telerik team
answered on 17 Feb 2012, 06:54 AM
Hello Jonathan,

This is not the expected behavior of the deleteItem(...) method. Could you provide complete aspx, javascript and code behind.

Regards, Tsvetoslav
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Jonathan
Top achievements
Rank 1
answered on 20 Feb 2012, 10:37 AM
Please find attached:

<%@ Control Language="c#" AutoEventWireup="True" Codebehind="AdditionProfileGrid.ascx.cs" Inherits="Hexagon.Web.UI.Generic.Grid.GridControls.AdditionProfileGrid" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<%@ Register TagPrefix="hexagon" Namespace="Hexagon.Web.UI.WebControls" Assembly="Hexagon.Web.UI" %>
<%@ Register TagPrefix="Search" TagName="Grid" Src="~/Generic/Grid/SearchGrid.ascx" %>
<%@ Register TagPrefix="gen" TagName="InputPrompt" Src="~/Generic/InputPrompt.ascx" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
 
<script type="text/javascript" language="javascript" src="<%= Hexagon.Web.UI.ApplicationHelper.TrueAppPath()%>Tree2/Scripts/Page.js"></script>
<script language="javascript" type="text/javascript" src="<%= Hexagon.Web.UI.ApplicationHelper.TrueAppPath()%>_scriptlibrary/detectbrowser.js"></script>   
<script language="Javascript">
 
	var RadGrid;
	var _orgCharThreshold = 2;
	var _orgsRefreshed = false;
	
	function GetGridObject()
	{
		RadGrid = $find('Wizard1_SearchUser_AdditionsGrid_SearchGrid_RadGrid1');
		RegisterDeleteAll();
	}
	
	function DeleteRow(index)
	{
		var masterTable = $find('Wizard1_SearchUser_AdditionsGrid_SearchGrid_RadGrid1').get_masterTableView();
		masterTable.deleteItem(masterTable.get_dataItems()[index].get_element());
    }
    
    function DeleteAllRows()
    {
		var gridRows = RadGrid.MasterTableView.get_dataItems();
		var numOfRows = gridRows.length;
		
		if(numOfRows > 0)
		{
			var lblError = document.getElementById('<%= lblInviteeError.ClientID %>');
			var answer = confirm('<%= resourceManager.GetString("confirmdeleteallnewusers") %>')
			if(answer)
			{
				for (var i = 0; i < numOfRows; i++)
				{
					DeleteRow(i);
				}
				setInnerText(lblError, '');
			}
		}
    }
    
    function RegisterDeleteAll()
    {
    	var radGrid = $find("Wizard1_SearchUser_AdditionsGrid_SearchGrid_RadGrid1");
 
    	if (radGrid.MasterTableView.HeaderRow != null)
		{
			var images = radGrid.MasterTableView.HeaderRow.getElementsByTagName('img');
			for(var i = 0; i < images.length; i++)
			{
				if(images[i].title.indexOf('<%= resourceManager.GetString("deleteallusers") %>') > -1)
				{
					var deleteAllBtn = images[i];
					break;
				}
			}
			if (deleteAllBtn != null)
			{
				deleteAllBtn.style.cursor = 'pointer';
				deleteAllBtn.onclick = DeleteAllRows;
				deleteAllBtn.value = '<%= resourceManager.GetString("confirmdeleteallnewusers") %>';
			}
		}
    }
    
    function SwitchShowRCB(textbox)
    {
		var textboxInfo = PageElement.getElementPositionInfo(textbox);
		var rcbOrg = $find("<%= rcbOrg.ClientID %>");
		var rcbOrgClient = document.getElementById("<%= rcbOrg.ClientID %>");
		var rcbOrgInput = document.getElementById("<%= rcbOrg.ClientID %>" + "_Input");
		
		rcbOrg.clearSelection();
 
		if (textbox.value != "")
		{
			var orgText = rcbOrg.findItemByText(textbox.value);
 
			if (orgText != null)
			{
				rcbOrgInput.value = textbox.value;
			}
		}
		if (CurrentBrowser.IE)
		{
			rcbOrgClient.style.top = textboxInfo.y - 10;
			rcbOrgClient.style.left = textboxInfo.x - 10;
			rcbOrgClient.style.width = textboxInfo.w + 5;
			rcbOrgClient.style.height = textboxInfo.h - 5;
		}
		else
		{
			rcbOrgClient.style.top = textboxInfo.y;
			rcbOrgClient.style.left = textboxInfo.x + 5;
			rcbOrgClient.style.width = textboxInfo.w;
			rcbOrgClient.style.height = textboxInfo.h;
		}
		rcbOrgClient.style.display = '';	
		
		rcbOrgInput.focus();
		rcbOrgInput.onblur =  function() { SetRCBOrg(textbox); };
    }
    
    function SetRCBOrg(txtBox)
    {
		var rcbOrg = $find("<%= rcbOrg.ClientID %>");
		var rcbOrgClient = document.getElementById("<%= rcbOrg.ClientID %>");
		var rcbOrgInput = document.getElementById("<%= rcbOrg.ClientID %>" + "_Input");
		
		if(rcbOrg.findItemByText(rcbOrgInput.value) != null)
		{
			txtBox.value = rcbOrgInput.value;
			rcbOrgClient.style.display = 'none';
		}
    }
	
	//case number 8213: display organisation details in invitations
	function ViewOrg(index)
	{
		var rcbOrgText = document.getElementById(index);
		
		if (rcbOrgText.value == '')
		{
			alert('<% = resourceManager.GetString("orghasnotbeenspecified") %>');
		}
		else
		{
			var rcbOrg = $find("<%= rcbOrg.ClientID %>");
			var org = rcbOrg.findItemByText(rcbOrgText.value);
			
			if (org != null)
			{
				var val = org._properties._data.value
				var text = org._properties._data.value;
			    
				document.getElementById('<%= hidCurrentRow.ClientID %>').value = index;
				
				if (val != "")
				{
					var textUrl = document.getElementById('<%= hidOrgUrl.ClientID %>').value;
					textUrl = textUrl + val + '&mode=popup&openerid=';
					window.open(textUrl,'','height=500,width=500,left='+(screen.width/2 - 200)+',top='+(screen.height/2 - 200)+',resizable=yes, scrollbars=yes');
				}
			}
        }
		
	}
	function FindDotNetControl(tagName,search)
    {
	    var array=document.getElementsByTagName(tagName);
		
	    for(var i = 0; i < array.length; i++)
	    { 
		    if(array[i].id.match(search))
			    return array[i];
	    }
		
	    return null;
	   }
 
 	function rcbOrg_OnClientItemsRequesting(sender, eventArgs)
 	{ 	    
 	    if (sender.get_text().length < _orgCharThreshold) {
 	        sender.hideDropDown();
 	        eventArgs.set_cancel(true);
 	    }
 	    else if (_orgsRefreshed)
 	    { 	        
 	        sender.clearCache();
 	    }
 	}
 
 	function rcbOrg_OnClientDropDownOpening(sender, eventArgs)
 	{ 	     	    
 	    eventArgs.set_cancel(true); 	    
 	    sender.clearItems(); // Prevents full list being shown for an instant on first load
 
 	    if (sender.get_text().length >= _orgCharThreshold)
 	    {
 	        eventArgs.set_cancel(false);
 	    } 	    
 	}
 
 	function rcbOrg_OnClientBlur(sender, eventArgs)
 	{
 	    var comboText = sender.get_text();
 	    var item = sender.findItemByText(comboText);
 	    //if there is no item with that text
 	    if (!item)
 	    { 	        
 	        sender.set_text("");
 	        setTimeout(function()
 	        {
 	            var inputElement = sender.get_inputDomElement();
 	        }, 20);
 	    }
 	    document.getElementById("<%= rcbOrg.ClientID %>").style.display = 'none';
 	}
 	
 	function ValidateInvitees(val, args)
 	{
 		var radGrid = $find("Wizard1_SearchUser_AdditionsGrid_SearchGrid_RadGrid1");
 		var gridRows = radGrid.MasterTableView.get_dataItems();
		var lblError = document.getElementById('<%= lblInviteeError.ClientID %>');
		var emailRegEx = /^(([a-zA-Z0-9_\.\-\'])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4}))$/;
 	
		if(gridRows == null)
		{
			setInnerText(lblError, '<%= resourceManager.GetString("noinvitee") %>');
			lblError.style.display = '';
			return args.IsValid = false;
		}
		else
		{
			var isValid				= false;
			var displayError		= '';
			var errorText			= '';
			var numOfChecked	= 0;
			var organisationtext	= '<%= resourceManager.GetString("organisation") %>';
			var forenametext		= '<%= resourceManager.GetString("forename") %>';
			var surnametext		= '<%= resourceManager.GetString("surname") %>';
			var emailtext			= '<%= resourceManager.GetString("Email") %>';
 			
			for (var i = 0; i < gridRows.length; i++)
			{
				var gridRowControl	= gridRows[i].get_element();
				var organisation	= getChildElement(gridRowControl, 'input''rcbOrgText');
				var forename		= getChildElement(gridRowControl, 'input''Forename');
				var surname			= getChildElement(gridRowControl, 'input''Surname');
				var email			= getChildElement(gridRowControl, 'input''Email');
				var checkbox		= getChildElement(gridRowControl, 'input''Selector');
 
				if (checkbox.checked)
				{
					numOfChecked++;	
						
					if (forename != null && forename.value == '')
					{
						errorText +=  '\n*<%= resourceManager.GetString("invalidinfo") %>'.replace('{0}', forenametext).replace('{1}', i+1);
					}
					if (surname != null && surname.value == '')
					{
						errorText +=  '\n*<%= resourceManager.GetString("invalidinfo") %>'.replace('{0}', surnametext).replace('{1}', i+1);
					}
					if ((email != null) && (email.value == '' || email.value.search(emailRegEx) == -1))
					{
						errorText +=  '\n*<%= resourceManager.GetString("invalidinfo") %>'.replace('{0}', emailtext).replace('{1}', i+1);
					}
					if((organisation != null) && (organisation.value == '' || organisation.value == ' ')) //single space is the loaded default for rcbOrg
					{
						errorText +=  '\n*<%= resourceManager.GetString("invalidinfo") %>'.replace('{0}', organisationtext).replace('{1}', i+1);
					}
				}
			}
 
			if (numOfChecked == 0)
			{
				setInnerText(lblError, '<%= resourceManager.GetString("noinvitee") %>');
				lblError.style.display = '';
				return args.IsValid = false;
			}
 			
			if(errorText == '')
			{
				isValid = true;
				displayError = 'none';
			}
 			
			lblError.style.display = displayError;
			setInnerText(lblError, errorText);
			return args.IsValid = isValid;
		}
 	}
 	
 	function chkSelect_onSelectedChanged(sender)
 	{
 		var toDisable = false;
 		if(!sender.checked)
 		{
 			toDisable = true;
 		}
 		
		var rowInputs = getParentElementByType(sender, 'tr').getElementsByTagName('input');
		for (var i = 0; i < rowInputs.length; i++)
		{
			if (rowInputs[i].id.indexOf('Selector') == -1)
			{
				rowInputs[i].disabled = toDisable;
			}
		}
 	}
 	
	function getChildElement(element, childType, childName)
	{
		var rtVal = null;
		
		if (element != null)
		{
			var fields = element.getElementsByTagName(childType);
			
			for (var j = 0; j < fields.length; j++)
			{
				if (fields[j].id.match(childName) == childName)
				{
					rtVal = fields[j];
					break;
				}		
			}
		}
		
		return rtVal;
	}
	
	function getParentElementByType(element, parentType)
	{
		var rtVal = null;
		
		parentType = parentType.toLowerCase()
		
		if (element != null)
		{
			if (element.tagName.toLowerCase() == parentType)
			{
				rtVal = element;
			}
			else if (element.parentNode == null)
			{
				rtVal = null;
			}
			else
			{
				rtVal = getParentElementByType(element.parentNode, parentType);
			}
		}
		
		return rtVal;
	}
 	
 	function setInnerText(element, text)
    {
        if (element.textContent == undefined)
        {
            element.innerText = text;
        }
        else
        {
            element.textContent = text;
        }        
    }
 
    function ValidateInviteeNum()
    {
		var inviteeNum = document.getElementById('<%= numOfNewUsers.ClientID %>');
		var errorlabel = document.getElementById('<%= lblInviteeError.ClientID %>');
		var loaderlabel = document.getElementById('<%= lblLoadingAdd.ClientID %>');
		
		if(isNaN(inviteeNum.value) || inviteeNum.value.indexOf('.') > -1 || inviteeNum.value <= 0)
		{
			errorlabel.style.display = '';
			setInnerText(errorlabel, '<%= resourceManager.GetString("invalidnumberofinvitees") %>');
			return false;
		}
		else
		{
			loaderlabel.style.display = '';
		}
    }
    
   function CancelNewInviteBubble(e)
	{
		var keynum;
		
	    if (window.event)
	    {
			keynum = e.keyCode;
		}
		else if (e.which)
		{
			keynum = e.which;
		}
		if(keynum == '13')
		{
			e.cancelBubble = true;
			e.returnValue = false;
 
			if (e.stopPropagation)
			{
				e.stopPropagation();
				e.preventDefault();
			}	
			document.getElementById('<%= btnAddNewUsers.ClientID %>').click();
		}
	}
	
	function ToggleShowAddInvitees()
	{
		var inviteeSection = document.getElementById('addNewInviteeSection');
		
		if(inviteeSection.style.visibility == 'hidden')
		{
			inviteeSection.style.visibility = 'visible';
		}
		else
		{
			inviteeSection.style.visibility = 'hidden';
		}
	}
 	
 	function tbEmail_valueChanged(tbEmail)
 	{
 	    /* Trim start and end of string for white space using regex.
 	     * Source: http://www.delphifaq.com/faq/f1031.shtml
 	     */ 	    
 	    tbEmail.value = tbEmail.value.replace(/^\s*/, '').replace(/\s*$/, '');
 	}
	     	
</script>
 
<style type="text/css">
    UL LI
    {
    	list-style-image:none;
    	list-style-position:outside;
    }
    .RadComboBoxDropDown .rcbItem
    {
    	padding-left : 0px;
    }    	
    .RadComboBoxDropDown .rcbHovered
    {
    	padding-left : 0px;
    }
    div.RadComboBox_MyDefault .rcbInputCell
    {
    	height10px;
    }
    
    .InputPrompt
    {
    	width200px;
    }
    
    #addnewselectorwindow
    {
    	background-colorWhite;
    	bordersolid 1px #7f9db9;
    }
    
    .numberToAdd
    {
		padding-left3px;
    }
 
</style>
 
<input type="hidden" id="hidCurrentRow" runat="server"/> 
<input type="hidden" id="hidOrgUrl" runat="server"/>
 
<div align=right style="width:90%">
	<table>
		<tr>
			<td>
				<asp:Image ID="imgIcon" ImageUrl="~/icons/people/s/user1_add.png" Runat=server></asp:Image>
				<hexagon:HexagonLinkButton id="cAddUser" runat="server" Text="Add New Invitee" OnClientClick="ToggleShowAddInvitees(); return false;"  CausesValidation="false" />
			</td>
			<td>
				<asp:Image ID="imgOrg" ImageUrl="~/icons/organisation_MN_16_B.png" Runat=server></asp:Image>
				<hexagon:hexagonpopuplinkbutton id="cAdd" runat="server" RefreshOnClose="false" text="Add New Organisation" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<div id="addNewInviteeSection" style="visibilityhidden;">
					<asp:Label ID="lblNumberToAdd" runat="server" CssClass="numberToAdd">Number of new users to add:</asp:Label>
					<input id="numOfNewUsers" type="text" runat="server" style="width30px;" maxlength="2" value="1" onkeydown="CancelNewInviteBubble(event);" /> 
					<asp:Button ID="btnAddNewUsers" runat="server" OnClientClick="return ValidateInviteeNum();" Text="Add" style="cursorpointer" CausesValidation="false" />
					<br />
					<asp:Label ID="lblLoadingAdd" runat="server" style="displaynonecolorGrayfont-weightbold;" />
				</div>
			</td>
		</tr>
	</table>
</div>
 
<div id="divRcbOrg">
	<telerik:RadComboBox ID="rcbOrg" runat="server" style="display:noneposition:absolute;"></telerik:RadComboBox>
</div>
 
<table border="0" width="90%" cellpadding=1 cellspacing=0>
	<tr>
		<td align=left>
			<gen:inputprompt id="cInputPrompt" runat="server" Name="People in this invitation" Description="Your invitation contains the following people."></gen:inputprompt>
		</td>
		<td align="right">
			<telerik:RadAjaxLoadingPanel id="LoadingPanel2" runat="server" IsSticky="true">
				<asp:Image id="LoadingImage" runat="server" ImageUrl="~/RadControls/Ajax/Skins/Default/LoadingProgressBar.gif"></asp:Image>
			</telerik:RadAjaxLoadingPanel>
		</td>
	</tr>
	<tr>
		<td colspan="2">		    
		    
			<Search:Grid id="SearchGrid" runat="server" StoreOnSession="false" XMLPath="~/Generic/Grid/GridXML/AdditionListView.xml"></Search:Grid>
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<br>
				<asp:CustomValidator ID="InviteeValidation" runat="server" ClientValidationFunction="ValidateInvitees" />
				<asp:Label ID="lblInviteeError" runat="server" style="color:Reddisplaynone;" />
		</td>
	</tr>
</table>


using System.Resources;
 
namespace Hexagon.Web.UI.Generic.Grid.GridControls
{
    using System;
    using System.Web.UI.WebControls;
    using Hexagon.BusinessObjects.Context;
    using Hexagon.BusinessObjects.Context.Additions;
    using Hexagon.BusinessObjects.Library;
    using Telerik.Web.UI;
	using Hexagon.BusinessObjects.Context.Additions.Helper;
	using System.Collections.Generic;
	using Hexagon.Web.UI.Invitations.CreationWizard;
    
 
	/// <summary>
	///		Summary description for AdditionProfileGrid.
	/// </summary>
	public partial class AdditionProfileGrid : BaseClasses.DetailViewControlBase
	{
 
		#region Member Variables
 
		protected Hexagon.Web.UI.Generic.Grid.SearchGrid SearchGrid;
        protected ResourceManager resourceManager = new ResourceManager("Hexagon.Web.UI.Generic.GenericResources", System.Reflection.Assembly.GetExecutingAssembly());
		public event EventHandler AddNewPersonToInvitation;
		public delegate void RowEventHandler(object sender, RowArgs e);
		protected FolderBase _currentContainer;
		protected Label lblInviteeError;
 
		#endregion
 
		protected void Page_Load(object sender, System.EventArgs e)
		{
			SearchGrid.GridControl.ClientSettings.ClientEvents.OnGridCreated="GetGridObject";
			SearchGrid.GridControl.ClientSettings.Selecting.AllowRowSelect = false;
			SearchGrid.LoadExternalAjax(SearchGrid.AjaxManager,LoadingPanel2);
            
		    cAddUser.Text = resourceManager.GetString("addnew");
            cAdd.Text = resourceManager.GetString("addorg");
		    cInputPrompt.Name = resourceManager.GetString("peopleininvitation");
		    cInputPrompt.Description = resourceManager.GetString("Invitecontainsfollowing");
			lblLoadingAdd.Text = resourceManager.GetString("loadingnewadds");
            //case number 8213: display organisation details in invitations
            hidOrgUrl.Value = Hexagon.Web.UI.Properties.OrganisationPropertiesPopup.BuildURLPath(); 
            
            if(!IsPostBack)
			{
				cAdd.NavigateToURL = Hexagon.Web.UI.Organisation.OrganisationWizardPage.BuildURL(UI.WizardControls.WizardLayoutMode.FILL, WizardControls.WizardEditMode.NEW, ""Guid.Empty, HostWindowContextContainerID);
				cAdd.PopupHeight = Hexagon.Web.UI.Organisation.OrganisationWizardPage.Height;
				cAdd.PopupWidth = Hexagon.Web.UI.Organisation.OrganisationWizardPage.Width;
				cAdd.Resizable = true;
			}
 
			ConfigureOrganisationControl(rcbOrg);
			BindOrganisations(rcbOrg);            
		}
 
		//Set the Grid Control Datasource.
		public override object DataSource
		{
			get
			{
				return SearchGrid.DataSource;
			}
			set
			{
				SearchGrid.DataSource = value;
			}
		}
 
		public void RemoveFromSession()
		{
			SearchGrid.RemoveFromSession();
		}
 
		public string APGSessionID
		{
			get
			{
				if (ViewState["APGSessionID"] == null)
				{
					APGSessionID = Guid.NewGuid().ToString();
				}
 
				return (string)ViewState["APGSessionID"];
			}
			set
			{
				ViewState["APGSessionID"] = value;
			}
		}
		public OrganisationFinder AvailableOrgs
		{
			get
			{
                OrganisationFinder rtVal;
				if(!SessionHelper.TryGetObject<OrganisationFinder>(APGSessionID + "Orgs"out rtVal))
				{
                    rtVal = OrganisationFinder.GetAdditionOrganisations(ApplicationHelper.GetTreeItem(HostWindowContextContainerID, false), HostWindowContextContainerID);
					AvailableOrgs = rtVal;
				}
 
                return rtVal;
			}
			set
			{
				SessionHelper.SetObject(APGSessionID + "Orgs"valueSessionHelper.SessionGroup.GENERAL);
			}
		}
		protected string NoInviteesError
		{
			get
			{
				return resourceManager.GetString("noinvitee");
			}
		}
		protected string InvalidInformation
		{
			get
			{
				return resourceManager.GetString("invalidinfo");
			}
		}
 
		/// <summary>
		/// Returns the client side assigned row index based on the client row click on the grid stored in a hidden field
		/// </summary>
		public int RowIndex
		{
			get
			{
				return Int32.Parse(hidCurrentRow.Value);
			}
		}
 
		/// <summary>
		/// RowArgs. Extends the EventArgs and adds params to be bubbled.
		/// </summary>
		public class RowArgs : EventArgs
		{
			public int RowIndex;
		}
 
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			SearchGrid.Grid_ItemDataBound += new GridItemEventHandler(SearchGrid_Grid_ItemDataBound);
			btnAddNewUsers.Click += new EventHandler(btnAddNewUsers_Click);
		}
		#endregion
 
 
        /// <summary>
        /// Binds the organisation drop down
        /// </summary>
        /// <param name="rcbxOrg">RadComboBox to bind</param>
        public void BindOrganisations(Telerik.Web.UI.RadComboBox rcbOrg)
        {
            // Populate the Organisations            
            rcbOrg.DataSource = AvailableOrgs;
            rcbOrg.DataTextField = "Name";
            rcbOrg.DataValueField = "GroupID";
            rcbOrg.DataBind();
        }
 
        /// <summary>
        /// Sets properties and client events for the Organisation RadComboBox
        /// </summary>
        /// /// <param name="rcbxOrg">RadComboBox to configure</param>        
        public void ConfigureOrganisationControl(Telerik.Web.UI.RadComboBox rcbOrg)
        {
            rcbOrg.EmptyMessage = resourceManager.GetString("notspecified");
            rcbOrg.EnableLoadOnDemand = true;
            rcbOrg.EnableItemCaching = true;
            rcbOrg.ShowDropDownOnTextboxClick = false;
            rcbOrg.ShowToggleImage = false;
            rcbOrg.MarkFirstMatch = false;
            rcbOrg.ShowWhileLoading = false;
            rcbOrg.ChangeTextOnKeyBoardNavigation = true;
            rcbOrg.Filter = Telerik.Web.UI.RadComboBoxFilter.StartsWith;
 
            //These client events are required to make the organisation dropdown safe in that it does not
            //show a full list of organisations to the user and only searches after 3 characters                    
            rcbOrg.OnClientItemsRequesting = "rcbOrg_OnClientItemsRequesting";
            rcbOrg.OnClientDropDownOpening = "rcbOrg_OnClientDropDownOpening";
            rcbOrg.OnClientBlur = "rcbOrg_OnClientBlur";
            
            rcbOrg.ItemsRequested += new Telerik.Web.UI.RadComboBoxItemsRequestedEventHandler(rcbOrg_ItemsRequested);            
            rcbOrg.Enabled = true;
        }
 
		/// <summary>
		/// Adds the checked grid items on wizard step change
		/// </summary>
		public void ApplyCheckedOnStepChange(StartInvitation.UIAdditions source)
		{
			int numOfDeleted = 0;
 
			foreach (GridDataItem editedItem in SearchGrid.GridControl.Items)
			{
				//Check if the check box is checked or unchecked
				if (!((CheckBox)editedItem.FindControl("Selector")).Checked)
				{
					source.RemoveAddition(source[editedItem.ItemIndex - numOfDeleted].ProfileID);
					numOfDeleted++;
				}
			}
		}
 
		/// <summary>
		/// Persist checked items for additional searches
		/// </summary>
		public void KeepCheckedOnSearch(StartInvitation.UIAdditions source)
		{
			int numOfDeleted = 0;
 
			foreach (GridDataItem editedItem in SearchGrid.GridControl.Items)
			{
				//Check if the check box is checked or unchecked
				if (!((CheckBox)editedItem.FindControl("Selector")).Checked)
				{
					source.RemoveAddition(source[editedItem.ItemIndex - numOfDeleted].ProfileID);
					numOfDeleted++;
				}
				else
				{
					source[editedItem.ItemIndex - numOfDeleted].Selected = true;
				}
			}
		}
 
		/// <summary>
		/// Re-checks the selected items on going back to the first wizard step
		/// </summary>
		public void ReApplyChecked()
		{
			foreach (GridDataItem editedItem in SearchGrid.GridControl.Items)
			{
				((CheckBox)editedItem.FindControl("Selector")).Checked = true;
			}
		}
 
		/// <summary>
		/// Re-applies checks of items on multiple user searches
		/// </summary>
		public void ReApplyCheckedOnSearch(StartInvitation.UIAdditions source)
		{
			foreach (GridDataItem editedItem in SearchGrid.GridControl.Items)
			{
				if (source[editedItem.ItemIndex].Selected)
				{
					((CheckBox)editedItem.FindControl("Selector")).Checked = true;
				}
			}
		}
 
		/// <summary>
		/// Saves all the data in the grid to the given ProfileAdditionBatch
		/// </summary>
		/// <param name="source"></param>
		public void SaveData(StartInvitation.UIAdditions source)
		{
            int previousNotSelected;
 
            previousNotSelected = 0;
 
 
			foreach (GridDataItem Item in SearchGrid.GridControl.Items)
			{
				System.Web.UI.WebControls.Image imgProfile = (System.Web.UI.WebControls.Image)Item.FindControl("Profile");
				CheckBox chkSelect = (CheckBox)Item.FindControl("Selector");
 
				if(chkSelect.Checked == true)
				{
					//Get the Document Datasource to update
					StartInvitation.UIAddition ds = source[Item.ItemIndex];
 
					if(!ds.Exists)
					{
						//First Name
						ds.FirstName = ((TextBox)Item.FindControl("Forename")).Text;
 
						//Last Name
						ds.LastName = ((TextBox)Item.FindControl("Surname")).Text;
 
						//Email
						ds.Email = ((TextBox)Item.FindControl("Email")).Text;
 
					}
                    //Organisation
                    TextBox rcbOrgText = (TextBox)Item.FindControl("rcbOrgText");
                    Guid orgID = new Guid();
					Telerik.Web.UI.RadComboBoxItem selectedOrg = rcbOrg.FindItemByText(rcbOrgText.Text);
                    if (selectedOrg != null)
                    {
                        orgID = new Guid(selectedOrg.Value);
                        ds.OrganisationID = orgID;
                        ds.OrganisationName = selectedOrg.Text;
                    }
 
                }
                else
                {
                    previousNotSelected++;
 
                }
 
			}
		}
 
		#region Events
 
		private void btnAddNewUsers_Click(object sender, EventArgs e)
		{
			if(AddNewPersonToInvitation != null)
			{
				AddNewPersonToInvitation(this.numOfNewUsers, e);
			}
		}
 
 
 
		/// <summary>
		///	SearchGrid_Grid_ItemDataBound. Bubbled event from the SearchGrid items binding to the grid.
		/// </summary>
		private void SearchGrid_Grid_ItemDataBound(object sender, GridItemEventArgs e)
		{
			if (e.Item.OwnerTableView.Parent is RadGrid)
			{
				if (e.Item.ItemType == GridItemType.Header)
				{
					((CheckBox)e.Item.FindControl("Selector")).Checked = true;
					((Image)e.Item.Cells[e.Item.Cells.Count - 2].Controls[0]).ToolTip = resourceManager.GetString("deleteallusers");
				}
 
				if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
				{
					StartInvitation.UIAddition ds = (StartInvitation.UIAddition)e.Item.DataItem;
					//Custom Column: Profile Image
					System.Web.UI.WebControls.Image imgProfile = (System.Web.UI.WebControls.Image)e.Item.FindControl("Profile");
					System.Web.UI.WebControls.Image imgDel = (System.Web.UI.WebControls.Image)e.Item.FindControl("Delete");
					CheckBox chkSelect = (CheckBox)e.Item.FindControl("Selector");
					Label rowCounter = (Label)e.Item.FindControl("RowCount");
					rowCounter.Text = (e.Item.RowIndex / 2).ToString() + ".";
 
						if (imgProfile != null)
						{
							if (ds.Exists)
							{
								imgProfile.ImageUrl = "~/icons/people/s/user1.png";
								imgProfile.Attributes.Add("Type""Exists");
								imgProfile.AlternateText = string.Format(resourceManager.GetString("existinguser"), ds.FirstName, ds.LastName);
								imgProfile.ToolTip = resourceManager.GetString("existingusertype");
							}
							else
							{
								imgProfile.ImageUrl = "~/icons/people/s/pawn_new.png";
								imgProfile.Attributes.Add("Type""New");
								imgProfile.AlternateText = string.Format(resourceManager.GetString("newuser"), ds.FirstName, ds.LastName);
								imgProfile.ToolTip = resourceManager.GetString("newusertype");
							}
 
							if (imgDel != null)
							{
								imgDel.ImageUrl = "~/icons/delete_SN_16_B.gif";
								imgDel.Attributes.Add("onclick""DeleteRow(" + e.Item.ItemIndex.ToString() + ");");
								imgDel.Style.Add("cursor""pointer");
								imgDel.ToolTip = resourceManager.GetString("deleteuser");
							}
						}
 
						//Custom Column: Organisation Image
						//case number 8213: display organisation details in invitations
						System.Web.UI.WebControls.Image imgOrg = (System.Web.UI.WebControls.Image)e.Item.FindControl("Organisation");
						if (imgOrg != null)
						{
							imgOrg.ImageUrl = "~/icons/ORGANISATIION_SV_16_B.gif";
							imgOrg.Attributes.Add("onclick""ViewOrg('" + e.Item.FindControl("rcbOrgText").ClientID.ToString() + "');");
							imgOrg.Style.Add("cursor""pointer");
						}
 
						//Get the rows custom controls
						TextBox tbForeName = (TextBox)e.Item.FindControl("Forename");
						TextBox tbSurname = (TextBox)e.Item.FindControl("Surname");
						TextBox tbEmail = (TextBox)e.Item.FindControl("Email");
 
						TextBox rcbOrgText = (TextBox)e.Item.FindControl("rcbOrgText");
						rcbOrgText.Attributes.Add("onfocus","SwitchShowRCB(" + rcbOrgText.ClientID.ToString() + ");");
						rcbOrgText.Attributes.Add("onclick","SwitchShowRCB(" + rcbOrgText.ClientID.ToString() + ");");
						rcbOrgText.Attributes.Add("readonly""true");
 
						Image includeFill = (Image)e.Item.FindControl("fill_rcbOrgText");
						includeFill.Attributes.CssStyle.Add("cursor""pointer");
 
						Telerik.Web.UI.RadComboBoxItem profileOrg = null;
 
						if (ds.OrganisationID != null && ds.OrganisationID != Guid.Empty)
						{
							profileOrg = rcbOrg.FindItemByValue(ds.OrganisationID.ToString());
 
							if (profileOrg != null)
							{
								ds.OrganisationName = profileOrg.Text;
								rcbOrgText.Text = profileOrg.Text;
							}
						}
						else if (ds.OrganisationName != null && ds.OrganisationName != string.Empty)
						{
							profileOrg = rcbOrg.FindItemByText(ds.OrganisationName);
 
							if (profileOrg != null)
							{
								ds.OrganisationID = new Guid(profileOrg.Value);
								rcbOrgText.Text = profileOrg.Text;
							}
						}
 
						if (!ds.Exists)
						{
							//Custom Column: First Name
							if (ds.FirstName != null && ds.FirstName != String.Empty)
							{
								tbForeName.Text = ds.FirstName.ToString();
							}
							//case number 7450:if it is a new User, put first letter of name and surname as capital letter 
							if (ds.FirstName != null && ds.FirstName != String.Empty)
							{
								tbForeName.Text = (((ds.FirstName).ToString())[0].ToString()).ToUpper() + (ds.FirstName).ToString().Substring(1, (ds.FirstName).ToString().Length - 1);
							}
							tbForeName.Width = 90;
							tbForeName.Height = 22;
 
							//Custom Column: Surname
							//case number 7450:if it is a new User, put first letter of name and surname as capital letter 
							if (ds.LastName != null)
							{
								tbSurname.Text = ds.LastName.ToString();
							}
							if (ds.LastName != null && ds.LastName != string.Empty)
							{
								tbSurname.Text = (((ds.LastName).ToString())[0].ToString()).ToUpper() + (ds.LastName).ToString().Substring(1, (ds.LastName).ToString().Length - 1);
							}
							tbSurname.Width = 90;
							tbSurname.Height = 22;
 
							//Custom Column: Email
							if (ds.Email != null)
							{
								tbEmail.Text = ds.Email.ToString();
							}
							tbEmail.Attributes.Add("onchange""tbEmail_valueChanged(this)");
							tbEmail.Width = 165;
							tbEmail.Height = 22;
 
							ds.Exists = false;
						}
						else
						{
							/* Setup Row for Existing RO user, Note I am adding then removing controls as placeholders cause problems when saving */
							//Custom Column: Forename
							Label lblForeName = new Label();
							lblForeName.Text = ds.FirstName.ToString();
							tbForeName.Parent.Controls.Add(lblForeName);
							tbForeName.Parent.Controls.Remove(tbForeName);
 
							//Custom Column: Surname
							Label lblSurname = new Label();
							lblSurname.Text = ds.LastName.ToString();
							tbSurname.Parent.Controls.Add(lblSurname);
							tbSurname.Parent.Controls.Remove(tbSurname);
 
							//Custom Column: Email
							Label lblEmail = new Label();
							lblEmail.Text = ds.Email.ToString();
							tbEmail.Parent.Controls.Add(lblEmail);
							tbEmail.Parent.Controls.Remove(tbEmail);
 
							ds.Exists = true;
						}
						//Custom Column: Selector
						if (ds.Exists)
						{
							chkSelect.ToolTip = "Check this box if you wish this existing user to be added to the invitation.";
						}
						else
						{
							chkSelect.ToolTip = "Check this box if you wish this new user to be added to the invitation.";
							chkSelect.Attributes.Add("onclick""chkSelect_onSelectedChanged(this)");
						}
						chkSelect.Checked = true;
				}
			}
		}
 
        /// <summary>
        /// Executed when the Organisation RadComboBox has 3 or more characters entered
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rcbOrg_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
        {
            Telerik.Web.UI.RadComboBox rcbOrg = (Telerik.Web.UI.RadComboBox)sender;
            BindOrganisations(rcbOrg);           
        }
 
		#endregion
 
 
	}
}
0
Jonathan
Top achievements
Rank 1
answered on 20 Feb 2012, 10:38 AM
Please note:

$find('<%=RadGrid1.ClientID=>') was always returning null so I have had to pass the exact name of the 
RadGrid Control

Jonathan
0
Elliott
Top achievements
Rank 2
answered on 20 Feb 2012, 03:06 PM
try
$find("<%= RadGrid1.ClientID %>")
Tags
Grid
Asked by
Jonathan
Top achievements
Rank 1
Answers by
Tsvetoslav
Telerik team
Jonathan
Top achievements
Rank 1
Elliott
Top achievements
Rank 2
Share this question
or