<telerik:AjaxSetting AjaxControlID="_btnSearch" EventName="OnClick" > <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"/> </UpdatedControls> </telerik:AjaxSetting><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %><!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>Untitled Page</title></head><body> <form id="form1" runat="server" autocomplete="false"> <div> <telerik:RadScriptManager ID="RadScriptManager" runat="server"> </telerik:RadScriptManager> <!-- content start --> <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"> <AjaxSettings> <telerik:AjaxSetting AjaxControlID="_btnSearch" EventName="OnClick" > <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"/> </UpdatedControls> </telerik:AjaxSetting> <telerik:AjaxSetting AjaxControlID="RadGrid1"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" /> </UpdatedControls> </telerik:AjaxSetting> </AjaxSettings> </telerik:RadAjaxManager> <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"> </telerik:RadAjaxLoadingPanel> <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="100%" Width="300px" OnLoad="RadAjaxPanel1_Load" > <table> <tr> <td style="width: 150px;"> Search By</td> <td style="width: 5px;"> :</td> <td style="width: 150px;"> <asp:DropDownList ID="_cboSearchBy" runat="server" Width="150px"> </asp:DropDownList> </td> <td style="width: 25px"> <asp:TextBox ID="_txtPrefix" runat="server" Width="25px" AutoPostBack="false" AutoCompleteType="none"></asp:TextBox></td> <td style="width: 200px;"> <asp:TextBox ID="_txtFind" runat="server" Width="200px" AutoPostBack="false" AutoCompleteType="none"></asp:TextBox></td> <td style="width: 25px"> <asp:TextBox ID="_txtSuffix" runat="server" Width="25px" AutoPostBack="false" AutoCompleteType="none"></asp:TextBox></td> <td style="width: 50px"> <asp:Button ID="_btnSearch" runat="server" Text="Search" Width="50px" OnClick="_btnSearch_Click" /> </td> </tr> </table> </telerik:RadAjaxPanel> <telerik:RadGrid ID="RadGrid1" Width="97%" AllowPaging="True" PageSize="15" runat="server" AllowSorting="true" OnNeedDataSource="RadGrid1_NeedDataSource" GridLines="None" OnItemCommand="RadGrid1_ItemCommand"> <MasterTableView Width="100%" EditMode="" AllowAutomaticUpdates="false"> <Columns> <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn" EditText="Edit" HeaderStyle-Width="30" ItemStyle-Width="30" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center"> </telerik:GridEditCommandColumn> </Columns> </MasterTableView> <PagerStyle Mode="NextPrevAndNumeric" /> <FilterMenu EnableTheming="True"> <CollapseAnimation Duration="200" Type="OutQuint" /> </FilterMenu> </telerik:RadGrid> <!-- content end --> </div> </form></body></html>public DataTable GetDataTable(string query) { String ConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(ConnString); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(query, conn); DataTable myDataTable = new DataTable(); conn.Open(); try { adapter.Fill(myDataTable); } finally { conn.Close(); } return myDataTable; } protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { RadGrid1.DataSource = GetDataTable("SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"); } protected void _btnSearch_Click(object sender, EventArgs e) { if (_txtFind.Text.Trim()!="") RadGrid1.DataSource = GetDataTable("SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers where CustomerID='" + _txtFind.Text.Trim() + "'"); else RadGrid1.DataSource = GetDataTable("SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"); RadGrid1.Rebind(); } protected void RadAjaxPanel1_Load(object sender, EventArgs e) { } protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e) { //e.Canceled = true; }I'm trying to use RadGrid inside RadMultiPage and noticed the problem with selecting grid rows on the client side.
Sometimes the get_selectedItems() method returns the array with valid number of items, but the items are undefined.
Please see the attached code.
Test scenario:
1. Start application, Data1 tab is activated.
2. Click checkbox inside GridClientSelectColumn header to select all rows.
3. Click [Test selected rows] button.
---> Problem: returned items are empty. Close the message box.
4. Click the row with ID=5 to select only this row.
5. Click [Test selected rows] button.
---> Works fine. Close the message box.
6: Click checkbox inside GridClientSelectColumn header to select all rows.
7. Click [Test selected rows] button.
---> Works fine. Close the message box.
8. Click the row with ID=5 to select only this row.
6. Click tab [Data2] to change tab.
7. Click tab [Data1] to return to first tab. Row with ID=5 is selected.
8. Click [Test selected rows] button.
---> Problem: returned item is empty. Close the message box.
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4.Default" %> <%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %> <!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></title> </head> <body> <form id="form1" runat="server"> <telerik:RadScriptBlock ID ="radScriptBlock" runat="server"> <script type="text/javascript"> function radTabStrip_TabSelecting(sender, args) { var tab = args.get_tab(); var multiPage = $find(sender.get_multiPageID()); var pageView = multiPage.findPageViewByID(tab.get_pageViewID()); if(pageView.get_element()) tab.set_postBack(false); } function btnTestSelectedItems1_Clicked(sender, args) { TestSelectedItems('<%= grdData1.ClientID %>'); } function btnTestSelectedItems2_Clicked(sender, args) { TestSelectedItems('<%= grdData2.ClientID %>'); } function btnTestSelectedItems3_Clicked(sender, args) { TestSelectedItems('<%= grdData3.ClientID %>'); } function TestSelectedItems(grd) { var items = $find(grd).get_selectedItems(); var msg = "Number of selected items: " + items.length + "\n\n"; for(var i = 0; i < items.length; i++) { msg += "Item" + i + ": "; var item = items[i]; if(item) msg += "ID = " + item.getDataKeyValue("ID"); else msg += "null"; msg += "\n" } alert(msg); } </script> </telerik:RadScriptBlock> <telerik:RadScriptManager ID="radScriptManager" runat="server" /> <telerik:RadAjaxLoadingPanel ID="radLoadingPanel" runat="server" /> <telerik:RadTabStrip ID="radTabStrip" runat="server" MultiPageID="radMultiPage" SelectedIndex="0" OnClientTabSelecting="radTabStrip_TabSelecting" OnTabClick="radTabStrip_TabClick"> <Tabs> <telerik:RadTab Text="Data1" PageViewID="pagData1"> </telerik:RadTab> <telerik:RadTab Text="Data2" PageViewID="pagData2"> </telerik:RadTab> <telerik:RadTab Text="Data3" PageViewID="pagData3"> </telerik:RadTab> </Tabs> </telerik:RadTabStrip> <telerik:RadMultiPage ID="radMultiPage" runat="server" SelectedIndex="0"> <telerik:RadPageView ID="pagData1" runat="server" Visible="false"> <telerik:RadGrid runat="server" ID="grdData1" AllowPaging="True" AllowSorting="True" AllowMultiRowSelection="True" ClientSettings-EnableRowHoverStyle="true" OnNeedDataSource="grdData_NeedDataSource"> <MasterTableView ClientDataKeyNames="ID"> <Columns> <telerik:GridClientSelectColumn /> </Columns> </MasterTableView> <ClientSettings EnableRowHoverStyle="true" Selecting-AllowRowSelect="true" /> </telerik:RadGrid> <telerik:RadButton ID="btnTestSelectedItems1" runat="server" Text="Test selected rows" AutoPostBack="false" OnClientClicked="btnTestSelectedItems1_Clicked" /> </telerik:RadPageView> <telerik:RadPageView ID="pagData2" runat="server" Visible="false"> <telerik:RadGrid runat="server" ID="grdData2" AllowPaging="True" AllowSorting="True" AllowMultiRowSelection="True" ClientSettings-EnableRowHoverStyle="true" OnNeedDataSource="grdData_NeedDataSource"> <MasterTableView ClientDataKeyNames="ID"> <Columns> <telerik:GridClientSelectColumn /> </Columns> </MasterTableView> <ClientSettings EnableRowHoverStyle="true" Selecting-AllowRowSelect="true" /> </telerik:RadGrid> <telerik:RadButton ID="btnTestSelectedItems2" runat="server" Text="Test selected rows" AutoPostBack="false" OnClientClicked="btnTestSelectedItems2_Clicked" /> </telerik:RadPageView> <telerik:RadPageView ID="pagData3" runat="server" Visible="false"> <telerik:RadGrid runat="server" ID="grdData3" AllowPaging="True" AllowSorting="True" AllowMultiRowSelection="True" ClientSettings-EnableRowHoverStyle="true" OnNeedDataSource="grdData_NeedDataSource"> <MasterTableView ClientDataKeyNames="ID"> <Columns> <telerik:GridClientSelectColumn /> </Columns> </MasterTableView> <ClientSettings EnableRowHoverStyle="true" Selecting-AllowRowSelect="true" /> </telerik:RadGrid> <telerik:RadButton ID="btnTestSelectedItems3" runat="server" Text="Test selected rows" AutoPostBack="false" OnClientClicked="btnTestSelectedItems3_Clicked" /> </telerik:RadPageView> </telerik:RadMultiPage> <telerik:RadAjaxManager runat="server" ID="radAjaxManager"> <AjaxSettings> <telerik:AjaxSetting AjaxControlID="radTabStrip"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="radTabStrip" /> <telerik:AjaxUpdatedControl ControlID="radMultiPage" LoadingPanelID="radLoadingPanel" /> </UpdatedControls> </telerik:AjaxSetting> </AjaxSettings> </telerik:RadAjaxManager> </form> </body> </html>
using System; using System.Data; using System.Web.UI; using Telerik.Web.UI; namespace WebApplication4 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!this.IsPostBack) this.pagData1.Visible = true; } protected void radTabStrip_TabClick(object sender, Telerik.Web.UI.RadTabStripEventArgs e) { e.Tab.PageView.Visible = true; e.Tab.PageView.Selected = true; foreach(Control control in e.Tab.PageView.Controls) if(control is RadGrid) ((RadGrid)control).Rebind(); } protected void grdData_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { ((RadGrid)sender).DataSource = this.GetDataTable(); } protected DataTable GetDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Day", typeof(string)); dt.Columns.Add("Date", typeof(DateTime)); Random r = new Random(); for(int i = 0; i < 100; i++) { DateTime dateTime = DateTime.Now.AddSeconds(-r.Next((int)TimeSpan.FromDays(365).TotalSeconds)); dt.Rows.Add(i + 1, dateTime.DayOfWeek.ToString(), dateTime); } return dt; } } } <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel4" runat="server" Skin="Black" /> <telerik:RadAjaxPanel ClientEvents-OnRequestStart="OnRequestStart" ID="RadAjaxPanel5" runat="server" > <telerik:raddockzone runat="server" id="RadDockZone6" Orientation=Vertical style="float:right;background: white;min-height:50" Width="99%" height="420" Skin="Black"> <telerik:raddock DefaultCommands=None OnCommand="RadDock_Command" EnableDrag=false runat="server" id="RadDock5" style="float:none;" title="" dockmode="Docked" Width="50%" Height="420" EnableAnimation="false" Skin="Black"> </telerik:raddock> </telerik:raddockzone></telerik:RadAjaxPanel>private void Notify(string strTitle, bool bsent = true){ if (DevicesRadGrid.SelectedItems.Count > 1) { if (bsent) NotificationText.Text = String.Format("sent {0}", DevicesRadGrid.SelectedItems.Count); else NotificationText.Text = "fail" } else { if (bsent) { GridDataItem gdi = (GridDataItem)DevicesRadGrid.SelectedItems[0]; NotificationText.Text = String.Format("sent to {0}, gdi["Client"].Text); } else NotificationText.Text = "fail"; } NotificationWindow.Title = strTitle; NotificationWindow.Visible = true; NotificationWindow.VisibleOnPageLoad = true; NotificationWindow.VisibleTitlebar = true; NotificationWindow.TitleIcon = ResolveUrl("~/Images/status/statusInfo.png");}<telerik:RadNotification ID="NotificationWindow" VisibleOnPageLoad="false" Visible="false" Position="TopCenter" KeepOnMouseOver="true" runat="server" ShowCloseButton="true" AutoCloseDelay="5000" TitleIcon="~/Images/status/statusInfo.png" Width="300px"> <NotificationMenu Visible="false"></NotificationMenu> <ContentTemplate> <asp:Label runat="server" Text="This is some display text" ID="NotificationText"></asp:Label> </ContentTemplate></telerik:RadNotification><script type="text/javascript" language="javascript"> function onTabSelecting(sender, args) { if (args.get_tab().get_pageViewID()) { args.get_tab().set_postBack(false); } //logEvent("OnClientTabSelecting: " + args.get_tab().get_text()); var str = args.get_tab().get_text(); if (str == "Premiums & Out Territory" || str == "Benefits" || str == "Deductibles") { var combo = $find("<%= ddlPolicyNo.ClientID %>"); var ddlnDate = document.getElementById("<%= ddlFromDate.ClientID %>"); var palnName = document.getElementById("<%= txtClassName.ClientID %>"); var comboItem = combo.get_text(); if (comboItem == "Select a PolicyNo") { alert("Select PolicyNo..."); var comboBox = $find('ddlPolicyNo'); var input = comboBox.get_inputDomElement(); input.focus(); str.set_selectedIndex(0); // document.getElementById("<%= radPlanMasterTab.ClientID%>").value = sender.SelectedTab.Text; return false; } if (ddlnDate.value == '') { alert("Select Inception Date..."); ddlnDate.focus(); str.set_selectedIndex(0); } if (palnName.value == '') { alert("Enter Plan Name..."); palnName.focus(); str.set_selectedIndex(0); } } if (str == "General & Eligibility" || str == "Benefits" || str == "Deductibles") { var txtGridCnt = document.getElementById('txtGridCnt') //alert(txtGridCnt.value); var ddlRelation = document.getElementById('ddlRelation'); if (ddlRelation.value == '' && (txtGridCnt.value == 0 || txtGridCnt.value == '')) { alert("Select the PremiumPlan"); document.getElementById('ddlRelation').focus(); str.set_selectedIndex(1); return false; } var txtBasic = document.getElementById('txtBasic'); var txtPolicyplantype = document.getElementById('txtPolicyplantype'); if ((txtBasic.value == '' && ddlRelation.text != '') && (txtGridCnt.value == 0 || txtGridCnt.value == '')) { alert("Enter the Basic ") document.getElementById('txtBasic').value = ""; document.getElementById('txtBasic').focus(); str.set_selectedIndex(1); return false; } if ((txtGridCnt.value == 0 || txtGridCnt.value == '')) { alert("Click on Add To Grid") str.set_selectedIndex(1); return false; } if (document.getElementById('chkOTAllowed').checked) { var txtOTRCRepPer = document.getElementById('txtOTRCRepPer'); if (txtOTRCRepPer.value == '') { alert("Enter the Out of Territory Reimbursement Claim Reporting Period") document.getElementById('txtOTRCRepPer').focus(); str.set_selectedIndex(1); return false; } var txtOTPerClaim = document.getElementById('txtOTPerClaim'); if (txtOTPerClaim.value == '') { alert("Enter the Percentage covered per Claim Out of Territory") document.getElementById('txtOTPerClaim').focus(); str.set_selectedIndex(1); return false; } var txtOTRoomChrg = document.getElementById('txtOTRoomChrg'); if (txtOTRoomChrg.value == '') { alert("Enter the Room Charges payable per Night in Out Territory") document.getElementById('txtOTRoomChrg').focus(); str.set_selectedIndex(1); return false; } var txtOTMaxEmpDay = document.getElementById('txtOTMaxEmpDay'); if (txtOTMaxEmpDay.value == '') { alert("Enter the Out Territory Max Member Days Covered") document.getElementById('txtOTMaxEmpDay').focus(); str.set_selectedIndex(1); return false; } var txtOTMaxDDay = document.getElementById('txtOTMaxDDay'); if (txtOTMaxDDay.value == '') { alert("Enter the Out Territory Max Dependants Days Covered") document.getElementById('txtOTMaxDDay').focus(); str.set_selectedIndex(1); return false; } } } } </script> <telerik:RadTabStrip ID="radPlanMasterTab" runat="server" MultiPageID="radPageView" Align="Justify" SelectedIndex="1" ReorderTabsOnSelect="True" Font-Names="Verdana" Font-Size="8.5pt" OnClientTabSelecting="onTabSelecting" Skin="Simple" Width="90%" > <Tabs> <telerik:RadTab Text="General & Eligibility" CssClass="SelectedTab" HoveredCssClass="a" SelectedCssClass="b" AccessKey="G" ToolTip="Alt+g" ></telerik:RadTab> <telerik:RadTab Text="Premiums & Out Territory" CssClass="SelectedTab" HoveredCssClass="a" SelectedCssClass="b" AccessKey="T" ToolTip="Alt+t" Selected="True"></telerik:RadTab> <telerik:RadTab Text="Benefits" CssClass="SelectedTab" HoveredCssClass="a" SelectedCssClass="b" AccessKey="B" ToolTip="Alt+b"></telerik:RadTab> <telerik:RadTab Text="Deductibles" CssClass="SelectedTab" HoveredCssClass="a" SelectedCssClass="b" AccessKey="U" ToolTip="Alt+u"></telerik:RadTab> </Tabs> </telerik:RadTabStrip><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EditFormComboWithOnLoad.aspx.cs" Inherits="Web.Test.EditFormComboWithOnLoad" %><!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></title></head><body> <form id="form1" runat="server"> <div> <telerik:RadScriptManager ID="radScriptManager" runat="server" EnablePartialRendering="true"> <Scripts> </Scripts> </telerik:RadScriptManager> <telerik:RadGrid ID="radGrid" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" GridLines="None" OnNeedDataSource="radGrid_NeedDataSource" OnItemDataBound="radGrid_ItemDataBound" OnUpdateCommand="radGrid_UpdateCommand" OnItemCommand="radGrid_ItemCommand"> <MasterTableView CommandItemDisplay="Top" AllowMultiColumnSorting="True" EditMode="PopUp" DataKeyNames="AddressId"> <RowIndicatorColumn> <HeaderStyle Width="20px"></HeaderStyle> </RowIndicatorColumn> <ExpandCollapseColumn> <HeaderStyle Width="20px"></HeaderStyle> </ExpandCollapseColumn> <Columns> <telerik:GridTemplateColumn UniqueName="country1" AllowFiltering="False" HeaderText="Address 1"> <ItemTemplate> <%# this.GetCountry1( Container.DataItem) %> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="country2" AllowFiltering="False" HeaderText="Address 2"> <ItemTemplate> <%# this.GetCountry2( Container.DataItem) %> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridTemplateColumn UniqueName="editColumn" AllowFiltering="False"> <ItemTemplate> <asp:ImageButton runat="server" ID="ibEdit" SkinID="IconEdit" CommandName="Edit" /> </ItemTemplate> <HeaderStyle Width="16px" /> <ItemStyle HorizontalAlign="Center" /> </telerik:GridTemplateColumn> </Columns> <EditFormSettings EditFormType="Template"> <EditColumn UniqueName="EditCommandColumn"> </EditColumn> <PopUpSettings Modal="True" /> <FormTemplate> <asp:Panel ID="Panel1" runat="server" DefaultButton="btnSave"> <fieldset style="margin: 5px; padding: 10px;"> <table> <tr> <td> <asp:Label ID="lblCountry1" runat="server" Text="Country 1:"></asp:Label> </td> <td> <telerik:RadComboBox ID="radCountryBox1" runat="server" EnableLoadOnDemand="False" MaxHeight="200px" AutoPostBack="true" ShowWhileLoading="false" MarkFirstMatch="true" Filter="StartsWith" OnSelectedIndexChanged="radCountryBox_SelectedIndexChanged"> </telerik:RadComboBox> </td> </tr> <td> <asp:Label ID="label2" runat="server" Text="Selected Value:"></asp:Label> </td> <td> <asp:Label ID="lblSelectedValue1" runat="server"></asp:Label> </td> <tr> <tr> <td> <asp:Label ID="lblCountry2" runat="server" Text="Country 2:"></asp:Label> </td> <td> <telerik:RadComboBox ID="radCountryBox2" runat="server" EnableLoadOnDemand="False" MaxHeight="200px" AutoPostBack="true" ShowWhileLoading="false" MarkFirstMatch="true" OnLoad="CountryBox2_Load" Filter="StartsWith" OnSelectedIndexChanged="radCountryBox2_SelectedIndexChanged"> </telerik:RadComboBox> </td> </tr> <td> <asp:Label ID="label3" runat="server" Text="Selected Value:"></asp:Label> </td> <td> <asp:Label ID="lblSelectedValue2" runat="server"></asp:Label> </td> <tr> </tr> </tr> </table> </fieldset> <table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-left: 5px;"> <tr> <td align="center"> <asp:Button runat="server" ID="btnSave" CommandName="Update" Text="Save" /> <asp:Button runat="server" ID="btnCancel" CommandName="Cancel" Text="Cancel" CausesValidation="false" /> </td> </tr> </table> </asp:Panel> </FormTemplate> </EditFormSettings> </MasterTableView> </telerik:RadGrid> </div> </form></body></html>using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Telerik.Web.UI;namespace Web.Test{ public partial class EditFormComboWithOnLoad : System.Web.UI.Page { #region FakeDataClasses private class Address { public int PartyId { get; set; } public int AddressId { get; set; } public int? Country1Id { get; set; } public int? Country2Id { get; set; } } private class Country { public int CountryId { get; set; } public string Name { get; set; } } #endregion private List<Country> _countries1; private List<Country> _countries2; private static List<Address> _addresses; public EditFormComboWithOnLoad() { CreateDummyCountries(); CreateDummyAddresses(); } #region SetupFakeData private void CreateDummyCountries() { _countries1 = new List<Country>(); _countries2 = new List<Country>(); AddDummyCountriesToList(_countries1); AddDummyCountriesToList(_countries2); } private void AddDummyCountriesToList(List<Country> countries) { Country country1 = new Country(); country1.CountryId = 1; country1.Name = "Country 1"; countries.Add(country1); Country country2 = new Country(); country2.CountryId = 2; country2.Name = "Country 2"; countries.Add(country2); Country country3 = new Country(); country3.CountryId = 3; country3.Name = "Country 3"; countries.Add(country3); Country country4 = new Country(); country4.CountryId = 4; country4.Name = "Country 4"; countries.Add(country4); } private void CreateDummyAddresses() { if (_addresses == null) { _addresses = new List<Address>(); Address pa = new Address(); pa = new Address(); pa.PartyId = 1; pa.AddressId = 1; pa.Country1Id = 1; pa.Country2Id = 2; _addresses.Add(pa); } } #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } int GetPartyId() { int partyId = 1; return partyId; } #region Grid Events protected void radGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { radGrid.DataSource = _addresses; } protected void radGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e) { try { int addressId = -1; if (e.Item.IsInEditMode && e.Item is GridEditFormItem) { GridEditFormItem editedItem = (GridEditFormItem)e.Item; // load CountryBox1 from code. Us OnLoad event to load CountryBox2 RadComboBox radCountryBox1 = ((RadComboBox)editedItem.FindControl("radCountryBox1")); CountryBox_Load(radCountryBox1, null); // We only want to bind the values for edit mode only if (!(e.Item is GridEditFormInsertItem)) { object primaryKey = editedItem.GetDataKeyValue("AddressId"); if (primaryKey != null) Int32.TryParse(primaryKey.ToString(), out addressId); Address address = null; if (addressId > 0) address = _addresses.Where(item => item.AddressId == addressId).FirstOrDefault(); if (address != null) { ((RadComboBox)editedItem.FindControl("radCountryBox1")).SelectedValue = address.Country1Id.ToString(); ((RadComboBox)editedItem.FindControl("radCountryBox2")).SelectedValue = address.Country2Id.ToString(); } } } } catch (Exception ex) { e.Canceled = true; } } protected void radGrid_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) { try { int addressId = -1; Address address = null; GridEditFormItem editedItem = e.Item as GridEditFormItem; // Conditional logic depending upon if we are inserting or updating if (e.Item is GridEditFormInsertItem) { address = new Address(); address.PartyId = GetPartyId(); address.AddressId = _addresses.Max(item => item.AddressId) + 1; } else { object primaryKey = editedItem.GetDataKeyValue("AddressId"); if (primaryKey != null) Int32.TryParse(primaryKey.ToString(), out addressId); if (addressId > 0) address = _addresses.Where(item => item.AddressId == addressId).FirstOrDefault(); } if (address != null) { address.Country1Id = TextUtility.TextToNullableInt(((RadComboBox)editedItem.FindControl("radCountryBox1")).SelectedValue.ToString()); address.Country1Id = (address.Country1Id == 0 ? null : address.Country1Id); address.Country2Id = TextUtility.TextToNullableInt(((RadComboBox)editedItem.FindControl("radCountryBox2")).SelectedValue.ToString()); address.Country2Id = (address.Country2Id == 0 ? null : address.Country2Id); if (e.Item is GridEditFormInsertItem) _addresses.Add(address); } else { throw new Exception("The record no longer exists."); } } catch (Exception ex) { e.Canceled = true; } } #endregion protected void CountryBox_Load(object sender, EventArgs e) { RadComboBox radBox = sender as RadComboBox; List<Country> data = _countries1; Country none = new Country(); radBox.DataSource = data; radBox.DataTextField = "Name"; radBox.DataValueField = "CountryId"; radBox.EmptyMessage = "Select a Country"; radBox.DataBind(); } protected void CountryBox2_Load(object sender, EventArgs e) { RadComboBox radBox = sender as RadComboBox; List<Country> data = _countries2; Country none = new Country(); radBox.DataSource = data; radBox.DataTextField = "Name"; radBox.DataValueField = "CountryId"; radBox.EmptyMessage = "Select a Country"; radBox.DataBind(); } protected void radCountryBox_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { int countryid; Int32.TryParse(e.Value, out countryid); Label lbl = (o as RadComboBox).Parent.FindControl("lblSelectedValue1") as Label; lbl.Text = countryid.ToString(); } protected void radCountryBox2_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { int countryid; Int32.TryParse(e.Value, out countryid); Label lbl = (o as RadComboBox).Parent.FindControl("lblSelectedValue2") as Label; lbl.Text = countryid.ToString(); } protected void radGrid_ItemCommand(object source, GridCommandEventArgs e) { if (e.CommandName.Equals(RadGrid.InitInsertCommandName)) { radGrid.MasterTableView.EditFormSettings.CaptionFormatString = "Adding new Address for Party"; } else if (e.CommandName.Equals(RadGrid.EditCommandName)) { radGrid.MasterTableView.EditFormSettings.CaptionFormatString = "Editing Address for Party"; } } protected string GetCountry1(object source) { // handle null object if (source == null) return "(null)"; string returnValue = string.Empty; Address item = (Address)source; if (item.Country1Id != null) returnValue = TextUtility.PruneText(_countries1.Where(countryItem => countryItem.CountryId == item.Country1Id).First().Name); else returnValue += "(null)"; return returnValue; } protected string GetCountry2(object source) { // handle null object if (source == null) return "(null)"; string returnValue = string.Empty; Address item = (Address)source; if (item.Country2Id != null) returnValue = TextUtility.PruneText(_countries2.Where(countryItem => countryItem.CountryId == item.Country2Id).First().Name); else returnValue += "(null)"; return returnValue; } public class TextUtility { public static string PruneText(string text) { return text; } public static int? TextToNullableInt(string text) { int value; if (int.TryParse(text, out value)) return value; else return (int?)null; } } } }//------------------------------------------------------------------------------// <auto-generated>// This code was generated by a tool.//// Changes to this file may cause incorrect behavior and will be lost if// the code is regenerated. // </auto-generated>//------------------------------------------------------------------------------namespace Web.Test { public partial class EditFormComboWithOnLoad { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// radScriptManager control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Telerik.Web.UI.RadScriptManager radScriptManager; /// <summary> /// radGrid control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Telerik.Web.UI.RadGrid radGrid; }}
What is the proper way to bind the 2nd radcombobox (cboUnit) that depends on a value from the 1st one (cboMission)?
I have tried a number of approaches with no success:
1. Declarative (in the aspx/ascx)? I set the datasourceid of the combobox cboUnit to the below entity data source.
A. I first put the following datasource control in the ascx file (outside of the <FormTemplate>) tag
<asp:EntityDataSource ID="sdsUnit" runat="server"
ContextTypeName="MiliTek.FleetBosse.FleetBosseEntities"
EnableFlattening="False" EntitySetName="vUnitMissions"
EntityTypeFilter="vUnitMission"
Select="it.CustID, it.CustomerName, it.UnitID,it.UnitName" Where="it.MissionID=@MissionID">
<WhereParameters>
<asp:ControlParameter ControlID="cboMission" Name="MissionID" PropertyName="SelectedValue" DbType="Int32" />
</WhereParameters>
</asp:EntityDataSource>
The page complains that it "Could not find control 'cboMission' in ControlParameter 'MissionID"
B. So I put the entity data source control inside the <formTemplate> tag. I now get a different error: The DataSourceID of 'cboUnit' must be the ID of a control of type IDataSource. A control with ID 'sdsUnit' could not be found.
C. I see that there is a onClientItemsRequested event but I don't want to use a webservice to bind to the combobox.
2. In the code behind?
A. You can't simply hook up the "ItemsRequested" handler as the code-behind does not have visibility of the combobox as they are wrapped within a <FormTemplate> tag.
B. I tried adding an event handler on the grid's ItemDataBound and ItemCreated event. I tried something like the below in one, then both of these events:
Dim cboUnit As RadComboBox = DirectCast(item.FindControl("cboUnit"), RadComboBox)
If cboUnit IsNot Nothing Then AddHandler cboUnit.ItemsRequested, AddressOf cboUnit_ItemsRequested
I've stepped through the code and see that the lines are executed, but every time I click the combobox, I get the dreaded "There is no assigned data source. Unable to complete callback request". The cboUnit_ItemsRequested method does not even get fired.
I then added the addhandler method within the 1st comboboxs selectedindexchanged event, but still get the same error.
I have turned of RadAjaxManager to see if that would resolve the problem but it still persists.
I'm ready to turn off load on demand if I can't figure this out - it is very frustrating. Can you tell me what I'm doing wrong?
Thank you,
Jim