Web Services
Top achievements
Rank 2
Web Services
asked on 20 Feb 2012, 07:57 PM
I have a rotator like so, that I bind in my code behind
I have some text boxes that do a post back. Whenever I do a post back, the rotator gets reset back to the first slide. I'm assuming I'll have to save whatever slide is current and set that, i just don't know how. Can you help me out with this?
<telerik:RadRotator ID="RadRotator1" runat="server" RotatorType="AutomaticAdvance" FrameDuration="5000" Width="600px" ItemWidth="600px" Height="445px" ItemHeight="445px" ScrollDirection="Left,Right" BorderColor="Black" BorderStyle="Groove" BorderWidth="2px"> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("fileName") %>' Width="600px" Height="445px" /> </ItemTemplate> <SlideShowAnimation Type="Fade"></SlideShowAnimation> </telerik:RadRotator>I have some text boxes that do a post back. Whenever I do a post back, the rotator gets reset back to the first slide. I'm assuming I'll have to save whatever slide is current and set that, i just don't know how. Can you help me out with this?
3 Answers, 1 is accepted
0
Richard
Top achievements
Rank 1
answered on 22 Feb 2012, 05:24 PM
Webservices,
In order to maintain state of the RadRotator currently selected slide on posting back, you'll need to reference and store the index of the current RadRotator item and set this as the InitialItemIndex property of the RadRotator control in code behind.
A solution for accomplishing this, creating a JavaScript function that gets attached to the OnClientItemShown event of the RadRotator, is provided in the maintaining item scroll position thru a postback? forum thread.
Hope this helps!
In order to maintain state of the RadRotator currently selected slide on posting back, you'll need to reference and store the index of the current RadRotator item and set this as the InitialItemIndex property of the RadRotator control in code behind.
A solution for accomplishing this, creating a JavaScript function that gets attached to the OnClientItemShown event of the RadRotator, is provided in the maintaining item scroll position thru a postback? forum thread.
Hope this helps!
0
Web Services
Top achievements
Rank 2
answered on 22 Feb 2012, 06:27 PM
Unfortunately, that code doesn't work for me as I am dynamically binding this. I tried it out, but I just get this error. Any ideas? here's my code.
relevant aspx
Code behind
Is there any way to fire an event on the server side when the rotator item changes?
relevant aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="showing.aspx.cs" Inherits="showing" %><%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="header" runat="server"> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <title></title> <style type="text/css"> </style> <link href="GreenRealty.css" rel="stylesheet" type="text/css" /> <script type="text/javascript">var currentIndex = 0; var hiddenField = null; function OnItemShown(sender, arg) { if (hiddenField == null) { // First loading hiddenField = document.getElementById("HiddenField1"); currentIndex = hiddenField.value; } hiddenField.value = currentIndex; // Store the index var lastIndex = sender.get_items().length - 1; if (currentIndex == lastIndex) { currentIndex = 0; } else { currentIndex++; } }<body style="background-image: url('images/topRepeat.png'); background-repeat: repeat-x;" > <form id="form1" runat="server"> <input id="HiddenField1" type="hidden" name="myHideField" runat="server" value="0" /> <telerik:RadScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </telerik:RadScriptManager> <div class="closeDiv"> <asp:LinkButton ID="close" runat="server" Text="Close" CssClass="closeButton" /> </div> <telerik:RadAjaxPanel ID="RadAjaxPanel3" runat="server" LoadingPanelID="RadAjaxLoadingPanel1"> <center> <table cellpadding="0" cellspacing="0" > <tr> <td style="width: 620px;" valign="top"> <div id="titleDiv"> <center> <img src="images/Green.png" /><br /> <asp:Label ID="subtitleOutput" runat="server" Font-Size="18px" Font-Bold="true"></asp:Label> </center> </div> <div id="powerPoint"> <telerik:RadRotator ID="RadRotator1" runat="server" RotatorType="AutomaticAdvance" FrameDuration="5000" Width="600px" ItemWidth="600px" Height="445px" ItemHeight="445px" ScrollDirection="Left,Right" BorderColor="Black" BorderStyle="Groove" BorderWidth="2px" OnClientItemShown="OnItemShown"> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("fileName") %>' Width="600px" Height="445px" /> </ItemTemplate> <SlideShowAnimation Type="Fade"></SlideShowAnimation> </telerik:RadRotator>Code behind
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.Sql;using System.Data.SqlClient;using Telerik.Web.UI;public partial class showing : System.Web.UI.Page{ MyFunctions obj = new MyFunctions(); String webPath = System.Configuration.ConfigurationManager.AppSettings["websitePath"]; String conn = System.Configuration.ConfigurationManager.ConnectionStrings["connString"].ToString(); protected void Page_Load(object sender, EventArgs e) { ////check if we need to set the focus //String focusSql = "SELECT currentTextBox FROM jsHolders"; //SqlConnection focusConn = new SqlConnection(conn); //SqlCommand focusCmd = new SqlCommand(focusSql, focusConn); //focusConn.Open(); //String textBoxId = ""; //SqlDataReader focusReader = focusCmd.ExecuteReader(); //while(focusReader.Read()){ // if (!(focusReader["currentTextBox"].ToString() == "no")) // { // textBoxId = focusReader["currentTextBox"].ToString(); // //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scroller", // // "<script type=\"text/javascript\">alert('" + focusReader["currentTextBox"].ToString() + "');</script>", false); // }//if focus reader //}//while focusReader.read // ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scroller", // "<script type=\"text/javascript\">document." + form1.ClientID.ToString() + "." + // textBoxId + ".focus();</script>", false); //focusConn.Close(); //setScroller(); String saleFk = Request.QueryString["saleId"]; //if this isn't a page post back then we populate the first power point and the grid view if (!(Page.IsPostBack)) { close.Attributes.Add("onclick", "javascript:window.open('', '_self');window.close();"); //set this to invisible initially exportPanel.Visible = false; //create the data table DataTable myTable = new DataTable(); myTable.Columns.Add("trackId"); myTable.Columns.Add("trackText"); myTable.Columns.Add("acres"); myTable.Columns.Add("owners"); myTable.Columns.Add("scroll"); //keep a counter for the first row Int16 count = 0; Int16 scrollTo = 0; //select all of the data for this sale String sql = "SELECT TrackId, uniqueFolder, trackName, acres, soldBy FROM tracks WHERE SaleFk = " + saleFk; using (SqlConnection myconn = new SqlConnection(conn)) { myconn.Open(); SqlCommand cmd = new SqlCommand(sql, myconn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()){ //if count is 0 we set it to 1 and set the first powerpoint to show if (count == 0) { count = 1; bindRotator(reader["TrackId"].ToString()); }//if count if (count >= 1) { scrollTo += 120; } decimal acre = (Decimal)reader["acres"]; String tempTrackText = "<span class='trackHeader'>" + reader["trackName"].ToString() + "</span><br />" + "<span class='acresText'>" + string.Format("{0:0,0.00}", acre) + " acres</span><br />"; //fill the datatable myTable.Rows.Add(reader["TrackId"].ToString(), tempTrackText, reader["acres"].ToString(), reader["soldBy"].ToString(), scrollTo); }//while reader.Close(); //populate the subtitle text sql = "SELECT subtitle FROM Subtitle"; cmd = new SqlCommand(sql, myconn); reader = cmd.ExecuteReader(); while (reader.Read()) { subtitleOutput.Text = reader["subtitle"].ToString(); }//while reader.read myconn.Close(); }//using //bind the gridview GridView1.DataSource = myTable; GridView1.DataBind(); count = 1; System.Drawing.Color red = System.Drawing.Color.FromArgb(227, 32, 40); //loop through the grid view to find the first unchecked box foreach (GridViewRow loopRow in GridView1.Rows) { //if this is true then we remove the css if (count == GridView1.Rows.Count) { loopRow.CssClass = ""; } //if this is one we set everything to red //and load the bid information else if(count == 1){ //get all of the current items Label trackOutputLabel = (Label)loopRow.FindControl("trackOutput"); Label dollarSignLabel = (Label)loopRow.FindControl("dollarSign"); TextBox perAcreInputTextBox = (TextBox)loopRow.FindControl("perAcreInput"); Label totalCostLabel = (Label)loopRow.FindControl("totalCost"); Label myAcreLabel = (Label)loopRow.FindControl("acreTextLabel"); Panel soldPanelBox = (Panel)loopRow.FindControl("soldPanel"); //set this current text to red trackOutputLabel.ForeColor = red; dollarSignLabel.ForeColor = red; perAcreInputTextBox.ForeColor = red; totalCostLabel.ForeColor = red; myAcreLabel.ForeColor = red; //get the total acres Label totalAcresLabel = (Label)loopRow.FindControl("acresHolder"); //get the owners Label ownersLabel = (Label)loopRow.FindControl("ownersHolder"); //load the current track information loadTrackInformation(perAcreInputTextBox.Text, totalAcresLabel.Text, ownersLabel.Text); } else { }//if count == rows.count count++; }//foreach }//if ! Page.ispost RadRotator1.InitialItemIndex = int.Parse(HiddenField1.Value); }//page load //if they checked the sold button protected void checkSoldChecked(object sender, EventArgs e) { String sql = "Update jsHolders set currentTextBox = 'no'"; SqlConnection myconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(sql, myconn); myconn.Open(); cmd.ExecuteNonQuery(); myconn.Close(); updateTrackPanel(); }//checkSoldChecked //this function loads the track information //in the main div protected void loadTrackInformation(String perAcre, String totalAcre, String owners) { string tempPerAcre; //see if this is nothing. if it is, then we set it to 0 if (perAcre == "") { tempPerAcre = "0.00"; perAcre = "0.00"; } else { tempPerAcre = string.Format("{0:0,0.00}", Convert.ToDecimal(perAcre) * Convert.ToDecimal(totalAcre)); }//if peracre String outputText = "$ " + string.Format("{0:0,0.00}", perAcre) + " x " + string.Format("{0:0,0.00}", Convert.ToDecimal(totalAcre)) + " acres<br /> Total: $" + tempPerAcre; currentBidOutput.Text = outputText; //if this is bigger than 52 then we make the text smaller if (owners.Length > 52) { ownersOutput.Text = "<span style='font-size: 22px;'>Owners: " + owners + "</span>"; } else { ownersOutput.Text = "Owners: " + owners; }//if owners.length }//loadBidInformation //this function updates the track panel to all of the correct sold/colors protected void updateTrackPanel() { String bindId = "blah"; System.Drawing.Color black = System.Drawing.Color.Black; System.Drawing.Color red = System.Drawing.Color.FromArgb(227, 32, 40); System.Drawing.Color green = System.Drawing.Color.FromArgb(3, 75, 39); //this will change if all items are checked Boolean allChecked = true; //loop through the grid view to find the first unchecked box foreach (GridViewRow loopRow in GridView1.Rows) { //get all of the current items Label trackOutputLabel = (Label)loopRow.FindControl("trackOutput"); Label dollarSignLabel = (Label)loopRow.FindControl("dollarSign"); TextBox perAcreInputTextBox = (TextBox)loopRow.FindControl("perAcreInput"); Label totalCostLabel = (Label)loopRow.FindControl("totalCost"); Label myAcreLabel = (Label)loopRow.FindControl("acreTextLabel"); Panel soldPanelBox = (Panel)loopRow.FindControl("soldPanel"); //get the checkbox CheckBox tempCheck = (CheckBox)loopRow.FindControl("soldCheck"); //get the current id //find the id Label myIdLabel = (Label)loopRow.FindControl("myTrackId"); String id = myIdLabel.Text.ToString(); //if the sold price is nothing then we insert 0 //other wise we enter the text Decimal tempPer; if(perAcreInputTextBox.Text.ToString() == ""){ tempPer = 0; }//if else{ tempPer = Convert.ToDecimal(perAcreInputTextBox.Text); }//if peracreinputtextbox.text == "" //update the sold for price String sql = "UPDATE Tracks SET SoldFor = '" + tempPer + "' WHERE TrackId = " + id; using (SqlConnection myconn = new SqlConnection(conn)) { myconn.Open(); SqlCommand cmd = new SqlCommand(sql, myconn); cmd.ExecuteNonQuery(); myconn.Close(); }//using //check to see if it isn't checked. if it isn't, then we show this current power point //on the first one and make sure the text is black and the sold panel is not visible if (!(tempCheck.Checked)) { allChecked = false; //set the colors trackOutputLabel.ForeColor = black; dollarSignLabel.ForeColor = black; perAcreInputTextBox.ForeColor = black; totalCostLabel.ForeColor = black; myAcreLabel.ForeColor = black; //***************************************************** //set the panel to invisible soldPanelBox.Visible = false; //***************************************************** //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "js" + id, // "<script type=\"text/javascript\">checkSold('" + id + "', '" + tempCheck.Checked + "');</script>", false); //if this = blah, then we bind the rotator as it is the first //unchecked track if (bindId == "blah") { bindId = id; //set this current text to red trackOutputLabel.ForeColor = red; dollarSignLabel.ForeColor = red; perAcreInputTextBox.ForeColor = red; totalCostLabel.ForeColor = red; myAcreLabel.ForeColor = red; //change the power point bindRotator(id); //get the total acres Label totalAcresLabel = (Label)loopRow.FindControl("acresHolder"); //get the owners Label ownersLabel = (Label)loopRow.FindControl("ownersHolder"); //load the current track information loadTrackInformation(perAcreInputTextBox.Text, totalAcresLabel.Text, ownersLabel.Text); }//if bindid }//if tempCheck.Checked //else we need to set the text to green and set the image since it is checked else { trackOutputLabel.ForeColor = green; dollarSignLabel.ForeColor = green; perAcreInputTextBox.ForeColor = green; totalCostLabel.ForeColor = green; myAcreLabel.ForeColor = green; //***************************************************** //set the sold panel to visible soldPanelBox.Visible = true; //***************************************************** //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "js" + id, // "<script type=\"text/javascript\">checkSold('" + id + "', '" + tempCheck.Checked +"');</script>", false); }//else }//for each //if this is true, then we show the export button if (allChecked) { mainOutputPanel.Visible = false; exportPanel.Visible = true; }//if allchecked else { mainOutputPanel.Visible = true; exportPanel.Visible = false; } }//updateTrackPanel //this function binds the rotator based on a track id you pass ing protected void bindRotator(String id){ //select all of the data for this sale String sql = "SELECT TrackId, uniqueFolder, trackName, acres, soldBy FROM tracks WHERE trackId = " + id; using (SqlConnection myconn = new SqlConnection(conn)) { myconn.Open(); SqlCommand cmd = new SqlCommand(sql, myconn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()){ //create the data table for the rad rotator System.Data.DataTable bindTable = new System.Data.DataTable(); //set the powerpoint bindTable = obj.returnImageTable(webPath + "powerPointImages\\" + reader["uniqueFolder"].ToString(), reader["uniqueFolder"].ToString()); //bind the rad rotator RadRotator1.DataSource = bindTable; RadRotator1.DataBind(); }//while }//using }//bindRotator //if they changed some text in the price text box protected void acrePriceChange(object sender, EventArgs e) { //Get the current row in grid GridViewRow currentRow = (GridViewRow)(sender as TextBox).Parent.Parent; //find the id Label myIdLabel = (Label)currentRow.FindControl("myTrackId"); String id = myIdLabel.Text.ToString(); //output.Text = id.ToString(); //find the acres and the text they've put in the box TextBox perAcreCostTextBox = (TextBox)currentRow.FindControl("perAcreInput"); Decimal perAcreCost = Convert.ToDecimal(perAcreCostTextBox.Text); //format the input to put back in the text box String perAcreFormat = string.Format("{0:0,0}", (perAcreCost)); perAcreCostTextBox.Text = perAcreFormat; //get the total acres Label totalAcresLabel = (Label)currentRow.FindControl("acresHolder"); Decimal totalAcres = Convert.ToDecimal(totalAcresLabel.Text); //calculate the total price String totalCost = string.Format("{0:0,0.00}", (perAcreCost * totalAcres)); //get the peracre textbox and set the text Label totalCostLabel = (Label)currentRow.FindControl("totalCost"); totalCostLabel.Text = "$" + totalCost + ""; updateTrackPanel(); //update the current textbox id then remove the numbers String textBoxId = perAcreCostTextBox.ClientID; String sql = "UPDATE jsHolders SET currentTextBox = '" + textBoxId + "'"; SqlConnection myconn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(sql, myconn); myconn.Open(); cmd.ExecuteNonQuery(); myconn.Close(); perAcreCostTextBox.Text = ""; }//acrePriceChange //this function sets the position of the scroller private void setScroller() { //select all of the data for this sale String sql = "SELECT scrollPos FROM ScrollPos"; using (SqlConnection myconn = new SqlConnection(conn)) { myconn.Open(); SqlCommand cmd = new SqlCommand(sql, myconn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scroller", "<script type=\"text/javascript\">setPosition('" + reader["scrollPos"] + "');</script>", false); }//while reader.read }//using }//setScroller //if they clicked the finish button protected void finishClick(object sender, EventArgs e) { Response.Redirect("Export.aspx?id=" + Request.QueryString["saleId"].ToString()); }//finishClick}//class showingIs there any way to fire an event on the server side when the rotator item changes?
0
Hello,
I created a sample page that uses the index persisting logic and the dynamic rebinding from your code sample and I modified a bit the client-side event handler OnItemShown in order to optimize it, but I wasn't able to encounter any problems with setting the index of the current RadRotator item. What is the exact error message that you have received and what is the exact behavior of problem? Please find attached my test sample and compare it with your actual project, so that you can check if I have missed something in my recreation.
I noticed that you are rebinding the RadRotator control with records from a database on a particular event. Note that the items that are populated in the controls may be fewer than before it is rebound and as a result the InitialItemIndex property of RadRotator will be set with index that references a non-existent element. You can add the following code after rebinding the RadRotator in order to ensure that the initial item index will always match an item from the control's Items collection:
If you are still having difficulties after examining the information provided above, please describe in detail the changes that should be made to the attached sample in order to reproduce the problem at hand. A fully runnable, simple page that isolates the issue will also be useful for examining your case and suggesting an according solution.
Greetings,
Slav
the Telerik team
I created a sample page that uses the index persisting logic and the dynamic rebinding from your code sample and I modified a bit the client-side event handler OnItemShown in order to optimize it, but I wasn't able to encounter any problems with setting the index of the current RadRotator item. What is the exact error message that you have received and what is the exact behavior of problem? Please find attached my test sample and compare it with your actual project, so that you can check if I have missed something in my recreation.
I noticed that you are rebinding the RadRotator control with records from a database on a particular event. Note that the items that are populated in the controls may be fewer than before it is rebound and as a result the InitialItemIndex property of RadRotator will be set with index that references a non-existent element. You can add the following code after rebinding the RadRotator in order to ensure that the initial item index will always match an item from the control's Items collection:
if (RadRotator1.InitialItemIndex >= RadRotator1.Items.Count){ RadRotator1.InitialItemIndex = RadRotator1.Items.Count - 1;}If you are still having difficulties after examining the information provided above, please describe in detail the changes that should be made to the attached sample in order to reproduce the problem at hand. A fully runnable, simple page that isolates the issue will also be useful for examining your case and suggesting an according solution.
Greetings,
Slav
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.