Select multiple colums from a radgrid with paging enabled

7 posts, 0 answers
  1. Anita
    Anita avatar
    13 posts
    Member since:
    Jan 2010

    Posted 09 Aug 2011 Link to this post

    Hi,

    I have a rad grid with paging enabled. I would like to select multiple records using check boxes.  The code is posted below. It doesn't work when items selected from more than one page. Any help would be appreciated.




      protected void ButtonApprove_Click(object sender, EventArgs e)
            {
                var UniqueIds = new List<string>();
                foreach (GridDataItem item in RadGrid1.MasterTableView.Items) // Loop through each items
                {
                    CheckBox chkBox = (CheckBox)item.FindControl("CheckBoxStatus"); // Get the checkbox control
                    if (chkBox.Checked)
                    {
                        var UniqueId = item["UniqueId"].Text;
                        UniqueIds.Add(UniqueId);                
                    }
                    
                }
                    foreach (var ss in UniqueIds)
                    {
                        var thisExpenseDetails = _repository.GetExpenseDetailsByUniqueID(ss);
                        thisExpenseDetails.Status = ExpensesClaimResource.StatusApproved;
                        _repository.SaveEntities();
                    }

                     RadGrid1.Rebind();
            }

    Thanks,
    Anita
  2. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 10 Aug 2011 Link to this post

    Hello Anita,

    RadGrid loses its current selection when the data is sorted, a new group or filter is added, or when the current page changes.Check the following help documentation which explains more about this.
    Persisting the Selected Rows Server-side on Sorting/Paging/Filtering/Grouping.

    Thanks,
    Princy.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Rakesh Gupta
    Rakesh Gupta avatar
    12 posts
    Member since:
    Oct 2010

    Posted 10 Aug 2011 Link to this post

    Hello Anita,

    RadGrid will lost the selected items when user changes the PageIndex.
    You cna use below code to remember the Selected Items on RadGrid PageIndex Change.
    -- aspx :
    <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" AllowMultiRowSelection="true"
    AllowPaging="true" AllowSorting="true" AllowCustomPaging="true" AllowMultiRowEdit="false"
    OnNeedDataSource="RadGrid1_NeedDataSource" EnableAjaxSkinRendering="true"
    ShowStatusBar="false" OnSortCommand="RadGrid1_SortCommand" OnItemDataBound="RadGrid1_ItemDataBound"
    OnItemCommand="RadGrid1_ItemCommand" OnPageIndexChanged="RadGrid1_PageIndexChanged">
    <PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true"></PagerStyle>
         <MasterTableView DataKeyNames="Id" CommandItemDisplay="Top" EnableNoRecordsTemplate="true"
          TableLayout="Auto" Width="100%" ClientDataKeyNames="Id">
         <Columns>
              <telerik:GridTemplateColumn HeaderText="Id" DataField="Id"
              SortExpression="Id" AllowFiltering="true" UniqueName="Id" Visible="true">
                   <HeaderStyle HorizontalAlign="Left" />
                   <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkJobItemId" CommandArgument='<%# Eval("Id") %>'
                        CommandName="Edit" Text='<%# Eval("Id") %>'></asp:LinkButton>
                   </ItemTemplate>
                   <ItemStyle Wrap="True" HorizontalAlign="Right" />
              </telerik:GridTemplateColumn>
         </Columns>
          /*Any Other Code*/
        </MasterTableView>
    </telerik:RadGrid>
    --- aspx.cs :
    --- Page Index Change :
    protected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)
    {
         RememberSelected(RadGrid1);
    }

    --- User Defined Method to Remember Selected Items :
    ArrayList selectedItems;
    private void RememberSelected(RadGrid radGrid)
    {
         selectedItems = new ArrayList();
         int index = -1;
     
         foreach (GridDataItem item in radGrid.Items)
         {
              index = (int)item.GetDataKeyValue("Id");
              bool result = item.Selected;
              // Check in the Session  
              if (ViewState["Selected"] != null)
                  selectedItems = (ArrayList)ViewState["Selected"];
                  if (result)
                  {
                       if (!selectedItems.Contains(index))
                           selectedItems.Add(index);
                  }
                  else
                      selectedItems.Remove(index);
          }
     
          if (selectedItems != null && selectedItems.Count > 0)
               ViewState["Selected"] = selectedItems;
    }

    --- Access Selected Item Method:
    private string GetSelectedItems()
    {
         string IdList = string.Empty;
         if (ViewState["Selected"] != null)
         {
              selectedItems = (ArrayList)ViewState["Selected"];
              for (int i = 0; i < selectedItems.Count; i++)
              {
                   IdList = IdList + (IdList == string.Empty ? "" : ",") + selectedItems[i];
              }
               ViewState["Selected"] = null;
         }
         foreach (GridItem item in RadGrid1.SelectedItems)
         {
              IdList = IdList + (IdList == string.Empty ? "" : ",") + ((LinkButton)item.FindControl("lnkId")).Text;
         }
         return IdList;
     }

    --- Read Selected Items On ItemCommand :
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string IdList = string.Empty;
        switch (e.CommandName)
        {
             case "Delete":
                  try
                  {
                       IdList = GetSelectedItems();
                       if (!string.IsNullOrEmpty(IdList ))
                       {
                          // Your Code Here
                       }
                  }
                  catch (Exception ex)
                  {
                       throw ex;
                  }
              break;
    }

    -- Check Previsouly Selected Items on Page Index Change (Item DataBound):
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
         try
         {
              if (selectedItems != null)
              {
                   if (e.Item is GridDataItem)
                   {
                        GridDataItem row = (GridDataItem)e.Item;
     
                        int index = (int)row.GetDataKeyValue("JobItemId");
     
                        if (selectedItems.Contains(index))
                        {
                             e.Item.Selected = true;
                        }
                   }
              }             
          }
          catch (Exception ex)
          {
              throw ex;
          }

    Let me know for any concerns.

    --
    Thanks & Regards,
    Rakesh T. Gupta
  5. Anita
    Anita avatar
    13 posts
    Member since:
    Jan 2010

    Posted 10 Aug 2011 Link to this post

    Sorry, I couldn't get it to work.
    The check box is  in GridTemplateColumn.
    A link (the first link in second post) in the following forum post seems releveant. But the link is broken!

    http://www.telerik.com/community/forums/aspnet/general-discussions/how-to-keep-the-checkbox-state-while-change-the-page.aspx

    Can you give me the correct url?

    Thanks,
    Anita

  6. Anita
    Anita avatar
    13 posts
    Member since:
    Jan 2010

    Posted 11 Aug 2011 Link to this post

    Hi Telerik team,

    This is my code. Can you please check what is missing here.

    ASPX page
      <telerik:GridTemplateColumn UniqueName="TemplateEditColumn" HeaderText="Select" AllowFiltering="false">
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBoxStatus" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBoxStatus_CheckedChanged" />
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>  

    onCheckedChanged

    protected void CheckBoxStatus_CheckedChanged(object sender, EventArgs e)
            {
                CheckBox chkbox = (CheckBox) sender;
                GridDataItem item = (GridDataItem) chkbox.NamingContainer;
                string value = item["FirstName"].Text;

                ArrayList selectedItems;
                if (Session["selectedItems"] == null)
                {
                    selectedItems = new ArrayList();
                }
                else
                {
                    selectedItems = (ArrayList)Session["selectedItems"];
                }

                if (chkbox.Checked)
                {
                    selectedItems.Add(value);
                }
                else
                {
                    selectedItems.Remove(value);
                }
                Session["selectedItems"] = selectedItems;
            }

    PreRender
     protected void RadGrid2_PreRender(object sender, EventArgs e)

            {

                if (Session["selectedItems"] != null)
                {
                    ArrayList selectedItems = (ArrayList) Session["selectedItems"];
                    Int16 stackIndex;
                    for (stackIndex = 0; stackIndex <= selectedItems.Count - 1; stackIndex++)
                    {
                        string curItem = selectedItems[stackIndex].ToString();

                        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
                        {
                           if (curItem.Equals(item["FirstName"].ToString()))
                           {
                               CheckBox chkbx = (CheckBox)item.FindControl("CheckBoxStatus");
                               chkbx.Checked = true;
                           }
                        }
                    }
                }
                

    Thanks,
    Anita


  7. Jayesh Goyani
    Jayesh Goyani avatar
    2732 posts
    Member since:
    May 2010

    Posted 11 Aug 2011 Link to this post

    Hello,

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TelerikTest.Web.WebForm2" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            </telerik:RadScriptManager>
            <telerik:RadGrid ID="RadGrid1" runat="server" GridLines="None" AllowPaging="True"
                AllowSorting="True" AutoGenerateColumns="False" AllowFilteringByColumn="True"
                OnNeedDataSource="RadGrid1_NeedDataSource" OnPreRender="RadGrid1_PreRender">
                <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
                <MasterTableView DataKeyNames="ID">
                    <Columns>
                        <telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID" SortExpression="ID">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Name" HeaderText="Name" UniqueName="Name" SortExpression="Name">
                        </telerik:GridBoundColumn>
                        <telerik:GridTemplateColumn>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" CausesValidation="false"
                                    OnCheckedChanged="CheckBox1_CheckedChanged" />
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                    </Columns>
                </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 TelerikTest.Web
    {
        public partial class WebForm2 : System.Web.UI.Page
        {
            public string _SelectedID
            {
                set
                {
                    ViewState["SelectedID"] = value;
                }
                get
                {
                    if (ViewState["SelectedID"] != null)
                    {
                        return Convert.ToString(ViewState["SelectedID"]);
                    }
                    else
                    {
                        return ",0,";
                    }
                }
     
            }
     
            protected void Page_Load(object sender, EventArgs e)
            {
     
            }
            protected void RadGrid1_PreRender(object sender, EventArgs e)
            {
     
                foreach (GridDataItem item in RadGrid1.Items)
                {
                    if (_SelectedID.Contains("," + Convert.ToInt32(item.GetDataKeyValue("ID")).ToString() + ","))
                    {
                        ((CheckBox)item.FindControl("CheckBox1")).Checked = true;
                    }
                }
     
            }
            protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
            {
                dynamic data = new[] {
                    new { ID = 1, Name ="Name1"},
                    new { ID = 2, Name = "Name2"},
                    new { ID = 3, Name = "Name3"},
                    new { ID = 4, Name = "Name4"},
                    new { ID = 5, Name = "Name5"},
                    new { ID = 6, Name ="Name6"},
                    new { ID = 7, Name = "Name7"},
                    new { ID = 8, Name = "Name8"},
                    new { ID = 9, Name = "Name9"},
                    new { ID = 10, Name = "Name10"},
                    new { ID = 11, Name ="Name11"},
                    new { ID = 12, Name = "Name12"},
                    new { ID = 13, Name = "Name13"},
                    new { ID = 14, Name = "Name14"},
                    new { ID = 15, Name = "Name15"}
                };
     
                RadGrid1.DataSource = data;
            }
            protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
            {
                CheckBox CheckBox1 = sender as CheckBox;
                GridDataItem item = (GridDataItem)CheckBox1.NamingContainer;
                int ID = Convert.ToInt32(item.GetDataKeyValue("ID"));
                if (CheckBox1.Checked)
                {
                    _SelectedID += ID.ToString() + ",";
                }
                else
                {
                    _SelectedID += _SelectedID.Replace(ID.ToString() + ",", "");
                }
            }
        }
    }

    let me know if any concern.

    Thanks,
    Jayesh Goyani

  8. Anita
    Anita avatar
    13 posts
    Member since:
    Jan 2010

    Posted 11 Aug 2011 Link to this post

    Thanks Rakesh & Jayesh.

    I finally managed to get it working.

    -Anita
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017