change row order radgrid

11 posts, 1 answers
  1. Duy
    Duy avatar
    24 posts
    Member since:
    Jun 2013

    Posted 27 Aug 2013 Link to this post

    is there a way to have a column with two images Up Down. depend on which image button you click on, it will move the row up or down and save the order into the database table.

    Please help. thanks
  2. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 28 Aug 2013 Link to this post

    Hi Duy,

    I guess you want two image buttons in each row , which moves the rows up and down.Please try the below code snippet to move a row up and down on the image button click.

    ASPX:
    <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="true" OnNeedDataSource="RadGrid1_NeedDataSource">
        <MasterTableView DataKeyNames="OrderID">
            <Columns>
                <telerik:GridBoundColumn UniqueName="OrderID" DataField="OrderID" HeaderText="OrderID" />
                <telerik:GridBoundColumn DataField="ShipCity" HeaderText="ShipCity" UniqueName="ShipCity" />
                <telerik:GridTemplateColumn>
                    <ItemTemplate>
                        <asp:ImageButton ID="Upbtn" runat="server" OnClick="Upbtn_Click" ImageUrl="~/RadGrid7/up.jpg"/>
                        <asp:ImageButton ID="Downbtn" runat="server" OnClick="Downbtn_Click" ImageUrl="~/RadGrid7/down.jpg"/>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

    C#:
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
       {
       RadGrid1.DataSource = this.DataSource;
       }
       public DataTable DataSource
       {
           get
           {
               object res = this.Session["_ds"];
               if (res == null)
               {
                   string selectQuery1 = "select top 10 OrderID,ShipCity from Orders";
                   SqlDataAdapter adapter1 = new SqlDataAdapter(selectQuery1, conn);
                   DataTable dt1 = new DataTable();
                   conn.Open();
                   adapter1.Fill(dt1);
                   conn.Close();
                   RadGrid1.DataSource = dt1;
                   this.Session["_ds"] = dt1;
               }
               return (DataTable)this.Session["_ds"];
           }
       }
     
    protected void Upbtn_Click(object sender, EventArgs e)
       {
           ImageButton upbtn = (ImageButton)sender;
           GridDataItem item = (GridDataItem)upbtn.NamingContainer;
           int index = item.ItemIndex;
           GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
           GridItem beforeItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index-1] as GridItem);
           object key1 = RadGrid1.MasterTableView.DataKeyValues[index]["OrderID"];
           object key2 = RadGrid1.MasterTableView.DataKeyValues[index - 1]["OrderID"];
           DataRow row1 = this.DataSource.Select(String.Format("OrderID = '{0}'", key1.ToString()))[0];
           DataRow row2 = this.DataSource.Select(String.Format("OrderID = '{0}'", key2.ToString()))[0];
           row1.BeginEdit();
           row2.BeginEdit();
           row2["OrderID"] = key1;
           row1["OrderID"] = key2;
           row1.EndEdit();
           row2.EndEdit();
           row1.AcceptChanges();
           row2.AcceptChanges();
           RadGrid1.Rebind();
       }
       protected void Downbtn_Click(object sender, EventArgs e)
       {
           ImageButton downbtn = (ImageButton)sender;
           GridDataItem item = (GridDataItem)downbtn.NamingContainer;
           int index = item.ItemIndex;
           GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
           GridItem afterItem= ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index + 1] as GridItem);
           object key1 = RadGrid1.MasterTableView.DataKeyValues[index]["OrderID"];
           object key2 = RadGrid1.MasterTableView.DataKeyValues[index + 1]["OrderID"];
           DataRow row1 = this.DataSource.Select(String.Format("OrderID = '{0}'", key1.ToString()))[0];
           DataRow row2 = this.DataSource.Select(String.Format("OrderID = '{0}'", key2.ToString()))[0];
           row1.BeginEdit();
           row2.BeginEdit();
           row2["OrderID"] = key1;
           row1["OrderID"] = key2;
           row1.EndEdit();
           row2.EndEdit();
           row1.AcceptChanges();
           row2.AcceptChanges();
           RadGrid1.Rebind();
       }

    Thanks,
    Princy
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Duy
    Duy avatar
    24 posts
    Member since:
    Jun 2013

    Posted 28 Aug 2013 Link to this post

    if i was to programmatically generate this at which event should i do this? itemcommand or itemdatabound or itemcreated? thank you Princy
  5. Answer
    Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 29 Aug 2013 Link to this post

    Hi Duy,

    I guess you are creating the entire grid programmatically,please try the below code snippet.

    ASPX:
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

    C#:
    public partial class RadGrid7_DynamicTemplate : System.Web.UI.Page
    {
        RadGrid grid;
        public static string connection = WebConfigurationManager.ConnectionStrings["Northwind_newConnectionString3"].ConnectionString;
        SqlConnection conn = new SqlConnection(connection);
        public SqlCommand SqlCommand = new SqlCommand();
     
        public DataTable DataSource
        {
            get
            {
                object res = this.Session["_ds"];
                if (res == null)
                {
                    string selectQuery1 = "select top 10 OrderID,ShipCity from Orders";
                    SqlDataAdapter adapter1 = new SqlDataAdapter(selectQuery1, conn);
                    DataTable dt1 = new DataTable();
                    conn.Open();
                    adapter1.Fill(dt1);
                    conn.Close();
                    grid.DataSource = dt1;
                    this.Session["_ds"] = dt1;
                }
                return (DataTable)this.Session["_ds"];
            }
        }
        protected void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            RadGrid RadGrid1 = (RadGrid)sender;
            RadGrid1.DataSource = this.DataSource;
        }
        protected void Page_Init(object sender, EventArgs e)
        {   //Creating the RadGrid
            grid = new RadGrid();
            grid.AutoGenerateColumns = false;
            grid.ID = "RadGrid1";
            grid.AllowPaging = true;
            grid.PageSize = 8;
            grid.Skin = "Outlook";
            grid.MasterTableView.DataKeyNames = new string[] { "OrderID" };
            grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource);
            grid.ItemCommand += new GridCommandEventHandler(grid_ItemCommand);      
            // Adding a bound Column
            GridBoundColumn boundColumn1 = new GridBoundColumn();
            grid.MasterTableView.Columns.Add(boundColumn1);
            boundColumn1.DataField = "OrderID";
            boundColumn1.UniqueName = "OrderID";
            boundColumn1.HeaderText = "OrderID";
            //Adding a Template Column
            string templateColumnName = "TemplateColumn";
            GridTemplateColumn templateColumn = new GridTemplateColumn();
            grid.MasterTableView.Columns.Add(templateColumn);
            templateColumn.ItemTemplate = new MyTemplate(templateColumnName);
            templateColumn.HeaderText = templateColumnName;
     
            PlaceHolder1.Controls.Add(grid);       
        }
        private class MyTemplate : ITemplate
        {
            private RadGrid7_DynamicTemplate _DynamicTemplte = new RadGrid7_DynamicTemplate();//Making Parent Class to be accessible in child class
            protected ImageButton upbtn,downbtn;      
            private string colname;
            public MyTemplate(string cName)
            {
                colname = cName;
            }
            public void InstantiateIn(System.Web.UI.Control container)
            {
                //Adding up button
                upbtn = new ImageButton();
                upbtn.ID = "upbtn";
                upbtn.ImageUrl = "~/RadGrid7/up.jpg";
                upbtn.CommandName = "up";
                upbtn.Height = Unit.Pixel(24);
                upbtn.Click += new ImageClickEventHandler(upbtn_Click);
                container.Controls.Add(upbtn);
     
                //Adding Down button
                downbtn = new ImageButton();
                downbtn.ID = "downbtn";
                downbtn.ImageUrl = "~/RadGrid7/down.jpg";
                downbtn.CommandName = "down";
                downbtn.Click+=new ImageClickEventHandler(downbtn_Click);         
                container.Controls.Add(downbtn);         
            }               
     
            void upbtn_Click(object sender, ImageClickEventArgs e)
            {
                ImageButton upbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)upbtn.NamingContainer;
                RadGrid RadGrid1 = (RadGrid)item.Parent.Parent.BindingContainer;
                int index = item.ItemIndex;
                GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
                GridItem beforeItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index - 1] as GridItem);
                object key1 = RadGrid1.MasterTableView.DataKeyValues[index]["OrderID"];
                object key2 = RadGrid1.MasterTableView.DataKeyValues[index - 1]["OrderID"];
                DataRow row1 = _DynamicTemplte.DataSource.Select(String.Format("OrderID = '{0}'", key1.ToString()))[0];
                DataRow row2 = _DynamicTemplte.DataSource.Select(String.Format("OrderID = '{0}'", key2.ToString()))[0];
                row1.BeginEdit();
                row2.BeginEdit();
                row2["OrderID"] = key1;
                row1["OrderID"] = key2;
                row1.EndEdit();
                row2.EndEdit();
                row1.AcceptChanges();
                row2.AcceptChanges();
                RadGrid1.Rebind();
            }
     
            void downbtn_Click(object sender, ImageClickEventArgs e)
            {
                ImageButton downbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)downbtn.NamingContainer;
                RadGrid RadGrid1 = (RadGrid)item.Parent.Parent.BindingContainer;
                int index = item.ItemIndex;
                GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
                GridItem afterItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index + 1] as GridItem);
                object key1 = RadGrid1.MasterTableView.DataKeyValues[index]["OrderID"];
                object key2 = RadGrid1.MasterTableView.DataKeyValues[index + 1]["OrderID"];
                DataRow row1 = _DynamicTemplte.DataSource.Select(String.Format("OrderID = '{0}'", key1.ToString()))[0];
                DataRow row2 = _DynamicTemplte.DataSource.Select(String.Format("OrderID = '{0}'", key2.ToString()))[0];         
                row1.BeginEdit();
                row2.BeginEdit();
                row2["OrderID"] = key1;
                row1["OrderID"] = key2;
                row1.EndEdit();
                row2.EndEdit();
                row1.AcceptChanges();
                row2.AcceptChanges();
                RadGrid1.Rebind();
            }
         }
        }      
     }

    Thanks,
    Princy
  6. Duy
    Duy avatar
    24 posts
    Member since:
    Jun 2013

    Posted 29 Aug 2013 Link to this post

    thank you for all your help. Princy
  7. Baker21
    Baker21 avatar
    4 posts
    Member since:
    Jul 2015

    Posted 08 Oct 2015 in reply to Princy Link to this post

    Hello,

    The first solution fits my situation and works precisely in code-behind, but reflects no changes on front-end. I googled and some references mentioned to to use NeedDataSource and set the data source of the radGrid to null and then rebind. Tried that as well, but no luck.. and client side errors either.. Like I said everything work precisely in code-behind...

    Any clue what could be the root cause for this?

  8. Baker21
    Baker21 avatar
    4 posts
    Member since:
    Jul 2015

    Posted 08 Oct 2015 in reply to Baker21 Link to this post

    Also ​any tip on how to make this work with pagination? 
  9. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 13 Oct 2015 Link to this post

    Hi Baker,

    Can you please share your page markup as well as the related code behind and also let us know what the exact client errors you are facing are? Thus we can revise the information locally and advise you further.

    Regards,
    Maria Ilieva
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  10. Baker21
    Baker21 avatar
    4 posts
    Member since:
    Jul 2015

    Posted 13 Oct 2015 in reply to Maria Ilieva Link to this post

    Hi Maria,

    Thank you for getting back to me. Here is the markup and code-behind:

    <telerik:RadGrid runat="server" ID="RadGrid1" AutoGenerateColumns="False" AllowPaging="True" EnableLinqExpressions="False"     
         OnNeedDataSource="RadGrid1_NeedDataSource" OnUpdateCommand="RadGrid1_UpdateCommand"
         OnItemCreated="RadGrid1_ItemCreated" OnDeleteCommand="RadGrid1_DeleteCommand" OnInsertCommand="RadGrid1_InsertCommand" >
         <GroupingSettings CaseSensitive="false" />                
         <MasterTableView DataKeyNames="AnnouncementId,LanguageID,ListOrder" CommandItemDisplay="Top" CommandItemSettings-ShowRefreshButton="true" >
             <Columns>
                 
                 <telerik:GridEditCommandColumn ButtonType="ImageButton" HeaderStyle-BorderStyle="None" HeaderStyle-Width="20px" HeaderStyle-Height="8px" ItemStyle-Height="8px"  HeaderStyle-CssClass="radGridManageButton" ItemStyle-CssClass="radGridManageButton" />
                 <telerik:GridButtonColumn ConfirmText="Delete this announcement?" ConfirmDialogType="RadWindow"
                     ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" HeaderStyle-BorderStyle="None"  
                     HeaderStyle-Width="20px"  HeaderStyle-Height="8px" ItemStyle-Height="8px"   
                     HeaderStyle-CssClass="radGridManageButton" ItemStyle-CssClass="radGridManageButton" />

                 <telerik:GridBoundColumn DataField="AnnouncementId" HeaderText="Announcement ID" ReadOnly="true" 
                     ForceExtractValue="Always" ConvertEmptyStringToNull="true" AllowFiltering="false" AllowSorting="false" 
                     ItemStyle-CssClass="displayNone" HeaderStyle-CssClass="displayNone" Display="false"/>
         
                 <telerik:GridBoundColumn DataField="Headline" HeaderText="Head Line"   ItemStyle-Width="200px" HeaderStyle-Width="200px" FilterControlWidth="90" />
                 <telerik:GridBoundColumn DataField="BodyText" HeaderText="Body Text"   ItemStyle-Width="200px" HeaderStyle-Width="200px" FilterControlWidth="90" />
         
                 <telerik:GridBoundColumn  DataField="StartDate" HeaderText="Start Date" DataType="System.DateTime" DataFormatString="{0:d}"   HeaderStyle-Width="150px" FilterControlWidth="90"/>
                 <telerik:GridBoundColumn DataField="EndDate" HeaderText="End Date" DataType="System.DateTime" DataFormatString="{0:d}" HeaderStyle-Width="150px" FilterControlWidth="90"/>           

                 <telerik:GridBoundColumn DataField="IsActive" HeaderText="Active" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px"/>
                 <telerik:GridBoundColumn DataField="AnnouncementDetails" HeaderText="Type" AllowFiltering="false" AllowSorting="false"  HeaderStyle-HorizontalAlign="Center"  
                     HeaderStyle-Width="80px"/>
         
                 <telerik:GridBoundColumn DataField="LanguageID" HeaderText="LanguageID" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px" Display="false"/>
                 <telerik:GridBoundColumn DataField="ListOrder" HeaderText="ListOrder" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px" Display="false"/>

                 <telerik:GridTemplateColumn HeaderText="Language" AllowFiltering="false" AllowSorting="false"  ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="150px"  FilterControlWidth="90">
                    <ItemTemplate> 
                      <asp:Label runat="server" ID="lbl_Language"  Text='<%# Enum.GetName(typeof(BuyerPortal.Common.enumLanguage), (int)Eval("LanguageID")).ToString() %>' />
                    </ItemTemplate>
                 </telerik:GridTemplateColumn>   
                                                                              
                 <telerik:GridTemplateColumn HeaderText="Re-Order" AllowFiltering="false" AllowSorting="false"  ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="80px">
                    <ItemTemplate> 
                        <div class="moveRowButtons">                                                
                                 <asp:ImageButton ID="Upbtn"    runat="server" OnClick="Upbtn_Click"      ImageUrl="~/Admin/Skins/Silk/images/up.png"    Width="10" Height="10" ListOrder='<%#Eval("ListOrder").ToString() %>' LanguageID='<%#Eval("LanguageID").ToString() %>' announcementid='<%#Eval("announcementid").ToString() %>' CssClass="upButton"    ToolTip="move row up" />
                                 <asp:ImageButton ID="Downbtn" runat="server" OnClick="Downbtn_Click"   ImageUrl="~/Admin/Skins/Silk/images/down.png"   Width="10" Height="10" ListOrder='<%#Eval("ListOrder").ToString() %>' LanguageID='<%#Eval("LanguageID").ToString() %>' announcementid='<%#Eval("announcementid").ToString() %>' CssClass="downButton"  ToolTip="move row down"/>
                        </div>                                     
                    </ItemTemplate>
                 </telerik:GridTemplateColumn>
         </Columns>
    </MasterTableView>
         <PagerStyle Mode="NextPrevAndNumeric" />                        
    </telerik:RadGrid>


    //--------------------
    //*** Codebehind
    //--------------------
    public DataTable DataSource
      {
          get
          {
              //list_announcement = db.GetAnnouncementsList(0, 1, out totalCount);                    
              //if (dtAnnouncements == null)
                  dtAnnouncements = db.GetAnnouncementsTable(0, 1, out totalCount);

              return dtAnnouncements;
          }
      }
    #region ragGridEvents

                protected void Rebind(object sender, CommandEventArgs e)
                {
                    //list_announcement = db.GetAnnouncementsList(0, 1, out totalCount);
                    //RadGrid1.DataSource = list_announcement;
                    RadGrid1.DataSource = this.DataSource;                
                }

                protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
                {
                    RadGrid1.DataSource = null;
                    RadGrid1.DataSource = this.DataSource;                
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "script_managemoveRowButtons", script_managemoveRowButtons, true);  
                }

                private void SetupInputManager(GridEditableItem editableItem)
                {
                    try
                    {
                    }
                    catch (System.Exception ex)
                    {
                        
                    }
                }

                protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
                {
                    if (e.Item is GridEditableItem && (e.Item.IsInEditMode))
                    {
                        GridEditableItem editableItem = (GridEditableItem)e.Item;
                        SetupInputManager(editableItem);
                    }
                }

                protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                        AddUpdate(e);
                    }
                    catch (System.Exception ex)
                    {
                        
                    }
                }

                protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                        AddUpdate(e);
                    }
                    catch (System.Exception ex)
                    {
                        
                    }
                }

                protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                    }
                    catch (System.Exception ex)
                    {
                        
                    }
                }
    #endregion

    #region moveRows
    protected void Upbtn_Click(object sender, EventArgs e)
            {
                ImageButton upbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)upbtn.NamingContainer;
                
                saveRowOrder(item.ItemIndex, "UP");
            }

            protected void Downbtn_Click(object sender, EventArgs e)
            {
                ImageButton downbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)downbtn.NamingContainer;            
                
                saveRowOrder(item.ItemIndex, "DOWN");
            }


    public void saveRowOrder(int currentIndex, string action)
            {
                int index = currentIndex;
                string rowAAnnouncementId = "", rowAListOrder = "", rowBAnnouncementId = "", rowBListOrder = "";
                if (action.Equals("DOWN"))
                    index++;
                else
                    index--;

                GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[currentIndex] as GridItem);
                GridItem afterItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
                string key1 = RadGrid1.MasterTableView.DataKeyValues[currentIndex]["ListOrder"].ToString();
                string key2 = RadGrid1.MasterTableView.DataKeyValues[index]["ListOrder"].ToString();
                int key1Lang = Convert.ToInt32(RadGrid1.MasterTableView.DataKeyValues[currentIndex]["LanguageID"].ToString());
                int key2Lang = Convert.ToInt32(RadGrid1.MasterTableView.DataKeyValues[currentIndex]["LanguageID"].ToString());

                if (key1Lang != key2Lang)
                {
                    DataRow row1 = this.DataSource.Select(String.Format("ListOrder = '{0}' AND LanguageID = '{1}'", key1, key1Lang.ToString()))[0];
                    DataRow row2 = this.DataSource.Select(String.Format("ListOrder = '{0}' AND LanguageID = '{1}'", key1, key1Lang.ToString()))[0];
    //above line throws an error.
    // i'm trying to move last record from page1 to page2
    //Error: 
    // Index was out of range. Must be non-negative and less than the size of the collection.
    // Parameter name: index
    //**Values:
    // currentIndex=9
    // index=10

                    rowAAnnouncementId = row1["AnnouncementId"].ToString();
                    rowAListOrder=  row1["ListOrder"].ToStringNullEmpty();
                    rowBAnnouncementId = row2["AnnouncementId"].ToStringNullEmpty();
                    rowBListOrder =  row2["ListOrder"].ToStringNullEmpty();

                    db.AnnouncementsRowOrderUpdate(rowAAnnouncementId, rowBListOrder,
                                                   rowBAnnouncementId, rowAListOrder);

                }
            }


    #endregion
     ​

  11. Baker21
    Baker21 avatar
    4 posts
    Member since:
    Jul 2015

    Posted 13 Oct 2015 Link to this post

    Hope this is more readable: 

     

     

     

    <telerik:RadGrid runat="server" ID="RadGrid1" AutoGenerateColumns="False" AllowPaging="True" EnableLinqExpressions="False"    
         OnNeedDataSource="RadGrid1_NeedDataSource" OnUpdateCommand="RadGrid1_UpdateCommand"
         OnItemCreated="RadGrid1_ItemCreated" OnDeleteCommand="RadGrid1_DeleteCommand" OnInsertCommand="RadGrid1_InsertCommand" >
         <GroupingSettings CaseSensitive="false" />               
         <MasterTableView DataKeyNames="AnnouncementId,LanguageID,ListOrder" CommandItemDisplay="Top" CommandItemSettings-ShowRefreshButton="true" >
             <Columns>
                  
                 <telerik:GridEditCommandColumn ButtonType="ImageButton" HeaderStyle-BorderStyle="None" HeaderStyle-Width="20px" HeaderStyle-Height="8px" ItemStyle-Height="8px"  HeaderStyle-CssClass="radGridManageButton" ItemStyle-CssClass="radGridManageButton" />
                 <telerik:GridButtonColumn ConfirmText="Delete this announcement?" ConfirmDialogType="RadWindow"
                     ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete" HeaderStyle-BorderStyle="None" 
                     HeaderStyle-Width="20px"  HeaderStyle-Height="8px" ItemStyle-Height="8px"  
                     HeaderStyle-CssClass="radGridManageButton" ItemStyle-CssClass="radGridManageButton" />
     
                 <telerik:GridBoundColumn DataField="AnnouncementId" HeaderText="Announcement ID" ReadOnly="true"
                     ForceExtractValue="Always" ConvertEmptyStringToNull="true" AllowFiltering="false" AllowSorting="false"
                     ItemStyle-CssClass="displayNone" HeaderStyle-CssClass="displayNone" Display="false"/>
          
                 <telerik:GridBoundColumn DataField="Headline" HeaderText="Head Line"   ItemStyle-Width="200px" HeaderStyle-Width="200px" FilterControlWidth="90" />
                 <telerik:GridBoundColumn DataField="BodyText" HeaderText="Body Text"   ItemStyle-Width="200px" HeaderStyle-Width="200px" FilterControlWidth="90" />
          
                 <telerik:GridBoundColumn  DataField="StartDate" HeaderText="Start Date" DataType="System.DateTime" DataFormatString="{0:d}"   HeaderStyle-Width="150px" FilterControlWidth="90"/>
                 <telerik:GridBoundColumn DataField="EndDate" HeaderText="End Date" DataType="System.DateTime" DataFormatString="{0:d}" HeaderStyle-Width="150px" FilterControlWidth="90"/>          
     
                 <telerik:GridBoundColumn DataField="IsActive" HeaderText="Active" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px"/>
                 <telerik:GridBoundColumn DataField="AnnouncementDetails" HeaderText="Type" AllowFiltering="false" AllowSorting="false"  HeaderStyle-HorizontalAlign="Center" 
                     HeaderStyle-Width="80px"/>
          
                 <telerik:GridBoundColumn DataField="LanguageID" HeaderText="LanguageID" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px" Display="false"/>
                 <telerik:GridBoundColumn DataField="ListOrder" HeaderText="ListOrder" AllowFiltering="false" AllowSorting="false"  HeaderStyle-Width="50px" Display="false"/>
     
                 <telerik:GridTemplateColumn HeaderText="Language" AllowFiltering="false" AllowSorting="false"  ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="150px"  FilterControlWidth="90">
                    <ItemTemplate>
                      <asp:Label runat="server" ID="lbl_Language"  Text='<%# Enum.GetName(typeof(BuyerPortal.Common.enumLanguage), (int)Eval("LanguageID")).ToString() %>' />
                    </ItemTemplate>
                 </telerik:GridTemplateColumn>  
                                                                               
                 <telerik:GridTemplateColumn HeaderText="Re-Order" AllowFiltering="false" AllowSorting="false"  ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="80px">
                    <ItemTemplate>
                        <div class="moveRowButtons">                                               
                                 <asp:ImageButton ID="Upbtn"    runat="server" OnClick="Upbtn_Click"      ImageUrl="~/Admin/Skins/Silk/images/up.png"    Width="10" Height="10" ListOrder='<%#Eval("ListOrder").ToString() %>' LanguageID='<%#Eval("LanguageID").ToString() %>' announcementid='<%#Eval("announcementid").ToString() %>' CssClass="upButton"    ToolTip="move row up" />
                                 <asp:ImageButton ID="Downbtn" runat="server" OnClick="Downbtn_Click"   ImageUrl="~/Admin/Skins/Silk/images/down.png"   Width="10" Height="10" ListOrder='<%#Eval("ListOrder").ToString() %>' LanguageID='<%#Eval("LanguageID").ToString() %>' announcementid='<%#Eval("announcementid").ToString() %>' CssClass="downButton"  ToolTip="move row down"/>
                        </div>                                    
                    </ItemTemplate>
                 </telerik:GridTemplateColumn>
         </Columns>
        </MasterTableView>
         <PagerStyle Mode="NextPrevAndNumeric" />                       
    </telerik:RadGrid>

     

     

    //--------------------
    //***   Codebehind
    //--------------------
    public DataTable DataSource
      {
          get
          {
              dtAnnouncements = db.GetAnnouncementsTable(0, 1, out totalCount);
              return dtAnnouncements;
          }
      }
    #region ragGridEvents
     
                protected void Rebind(object sender, CommandEventArgs e)
                {
                    RadGrid1.DataSource = this.DataSource;               
                }
     
                protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
                {
                    RadGrid1.DataSource = null;
                    RadGrid1.DataSource = this.DataSource;               
                }
     
                private void SetupInputManager(GridEditableItem editableItem)
                {
                    try
                    {
                    }
                    catch (System.Exception ex)
                    {
                         
                    }
                }
     
                protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
                {
                    if (e.Item is GridEditableItem && (e.Item.IsInEditMode))
                    {
                        GridEditableItem editableItem = (GridEditableItem)e.Item;
                        SetupInputManager(editableItem);
                    }
                }
     
                protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                        AddUpdate(e);
                    }
                    catch (System.Exception ex)
                    {
                         
                    }
                }
     
                protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                        AddUpdate(e);
                    }
                    catch (System.Exception ex)
                    {
                         
                    }
                }
     
                protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
                {
                    try
                    {
                        string strCommand = e.CommandName.ToString();
                    }
                    catch (System.Exception ex)
                    {
                         
                    }
                }          
    #endregion 
     
    #region moveRows
            protected void Upbtn_Click(object sender, EventArgs e)
            {
                ImageButton upbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)upbtn.NamingContainer;
                 
                saveRowOrder(item.ItemIndex, "UP");
            }
     
            protected void Downbtn_Click(object sender, EventArgs e)
            {
                ImageButton downbtn = (ImageButton)sender;
                GridDataItem item = (GridDataItem)downbtn.NamingContainer;           
                 
                saveRowOrder(item.ItemIndex, "DOWN");
            }
             
             
            public void saveRowOrder(int currentIndex, string action)
            {
                int index = currentIndex;
                string rowAAnnouncementId = "", rowAListOrder = "", rowBAnnouncementId = "", rowBListOrder = "";
                if (action.Equals("DOWN"))
                    index++;
                else
                    index--;
     
                GridItem movedItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[currentIndex] as GridItem);
                GridItem afterItem = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[index] as GridItem);
                string key1 = RadGrid1.MasterTableView.DataKeyValues[currentIndex]["ListOrder"].ToString();
                string key2 = RadGrid1.MasterTableView.DataKeyValues[index]["ListOrder"].ToString();
                int key1Lang = Convert.ToInt32(RadGrid1.MasterTableView.DataKeyValues[currentIndex]["LanguageID"].ToString());
                int key2Lang = Convert.ToInt32(RadGrid1.MasterTableView.DataKeyValues[currentIndex]["LanguageID"].ToString());
     
                if (key1Lang != key2Lang)
                {
                    DataRow row1 = this.DataSource.Select(String.Format("ListOrder = '{0}' AND LanguageID = '{1}'", key1, key1Lang.ToString()))[0];            
                    DataRow row2 = this.DataSource.Select(String.Format("ListOrder = '{0}' AND LanguageID = '{1}'", key1, key1Lang.ToString()))[0];
                    //above line throws an error.
                    // i'm trying to move last record from page1 to page2
                    //Error:
                    //      Index was out of range. Must be non-negative and less than the size of the collection.
                    //      Parameter name: index
                    //**Values:
                    //      currentIndex=9
                    //      index=10
                     
                    rowAAnnouncementId = row1["AnnouncementId"].ToString();
                    rowAListOrder=  row1["ListOrder"].ToStringNullEmpty();
                    rowBAnnouncementId = row2["AnnouncementId"].ToStringNullEmpty();
                    rowBListOrder =  row2["ListOrder"].ToStringNullEmpty();
     
                    db.AnnouncementsRowOrderUpdate(rowAAnnouncementId, rowBListOrder,
                                                   rowBAnnouncementId, rowAListOrder);
     
                }
            }
             
             
    #endregion 

  12. Maria Ilieva
    Admin
    Maria Ilieva avatar
    4017 posts

    Posted 15 Oct 2015 Link to this post

    Hi Baker,

    I revise the provided code and was not able to isolate anything obvious that may lead to the problematic behavior. In this case I would kindly ask you to open a regular support ticket and send us sample runnable version of your application as well as exact steps for replicating the issue. Thus we will be able to debug it locally and advise you further.

    Regards,
    Maria Ilieva
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017