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

Create Grid programmatically

9 Answers 217 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Carla
Top achievements
Rank 1
Carla asked on 07 Apr 2014, 04:15 PM
Hi everyone! I'm working on a WebPart containing a RadGrid created programmatically (by code behind) with a filterchecklist; There are 3 aspects that I would like to ask for help:

1) RadGrid1.MasterTableView.FilterExpression is always an empty String! I need to use it in the handler method for "OnNeedDataSource" to filter the grid:

            String filterExpression = RadGrid1.MasterTableView.FilterExpression;
            DataFiltered = Data.Select(filterExpression, Data.Columns[0].ColumnName + " ASC").CopyToDataTable();
            RadGrid1.DataSource = DataFiltered;

But when i check\uncheck items of checklist or use the "Classic" filter it does not work and is always an empty String.

2) I need for my purpose to check\uncheck the items of the checklist programmatically based on informations that i only know in the code behind; since the attribute Checked for an element of type RadListBoxItem doesn't work, my idea is to save this information within the handler method for OnFilterCheckListItemsRequested, for example within the attribute "Item.value":

        public void RadGrid1_NeedCheckListItems(object sender, GridFilterCheckListItemsRequestedEventArgs e)
        {
          ........
                RadListBoxItem Item = new RadListBoxItem();
                Item.Text =Convert.ToString(Data[row_index][col_index]);
                Item.Value = isFiltered? "FILTER" "NOFILTER";
                e.ListBox.Items.Add(Item);
          ........
        }

In the .aspx page of the webpart, I can check the e.ListBox.Items elements using the following code:

       var gridPrototype = Telerik.Web.UI.RadGrid.prototype;
       gridPrototype._checkListItemsRequestedHandlerOriginal = gridPrototype._checkListItemsRequestedHandler;
       gridPrototype._checkListItemsRequestedHandler = function () {
            this._checkListItemsRequestedHandlerOriginal(); // call the origianl method
            var filterCheckList = $find(this._filterCheckListClientID); // get the check list
            var column = this._checkListFilterActiveColumn.get_uniqueName(); // get the active column
            filterCheckList.get_items().getItem(0).check(); // check the first item for example
       }

How can i access the length of the listbox and the attribute "value" of a single item? My purpose is to scan the listbox until its end (that's why i need the length of this list) and check the attribute "value" of a single item to decide if check or uncheck this RadListBoxItem?
Is it also possible to set the attribute "value" to modify it after you've read it?

3) Less important thing, As you can see in the attached file, what tag i can use in the ".RadFilterMenu_CheckList css class" to make sure that "Cancel" button is alligned with "Apply" button?

Thanks in advance, (unfortunately without the source code i don't know where to find these informations).

Regards,
Carla

9 Answers, 1 is accepted

Sort by
0
Kostadin
Telerik team
answered on 10 Apr 2014, 01:48 PM
Hello Carla,

Straight to your questions:
  1. After applying a filter and NeedDataSource is fired I am able to access the applied filter expression on this event. I prepared a small sample and attached it to this forum thread. Please check it out and let me know about the result.
  2. I am not sure I completely understand your requirement. Are you trying to get the length of the ListBox on the client side? If that is your requirement then you could use the following approach.
    <script type="text/javascript">
        var count = 0;
        Telerik.Web.UI.RadGrid.prototype._checkListItemsRequestedHandler = function(){
            count = $find(this._filterCheckListClientID).get_items().get_count();
            debugger;
        }
     
    </script>
    Note that you could access the filter menu only on client. Also please keep in mind that by selecting items in the ListBox, the grid will not filtered without clicking the Apply button. So in this case if you try to filter the grid you have to create and apply a filter expression in your code behind. I would appreciate if you could provide more detailed information about you requirement.
  3. It looks like you have some global css rules which overrides the default style of the buttons. For instance if you have a global width of the input element then this might break the default look of the apply and cancel buttons.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Carla
Top achievements
Rank 1
answered on 10 Apr 2014, 04:19 PM
Hi Kostadin, i'll try to be as much detailed as possible (also posting my code): my purpose is to create a webpart containing a RadGrid with filterchecklist (this Grid is created dinamically by code behind on the "onLoad" handler, so in the .aspx page the Grid is empty).

.aspx:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Telerik.Web.UI, Version=2014.1.225.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI, Version=2014.1.225.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RadGridWebPartUserControl.ascx.cs" Inherits="CheckListFiltering.RadGridWebPart.RadGridWebPartUserControl" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
  <style type="text/css">
  .HoverClass
  
      background-color: aqua;
  }
  .DefaultClass
  {
      background-color: white;
  }
  .ClickClass
  {
      background-color: yellow;
  }
  .RadFilterMenu_CheckList
  {
      max-height: 200px !important;
      height: 200px !important;
      width: 200px !important;
  }
  </style>
  <script type="text/javascript">
//      var gridPrototype = Telerik.Web.UI.RadGrid.prototype;
//      gridPrototype._checkListItemsRequestedHandlerOriginal = gridPrototype._checkListItemsRequestedHandler;
//      gridPrototype._checkListItemsRequestedHandler = function () {
//          this._checkListItemsRequestedHandlerOriginal(); // call the origianl method
 
//          var filterCheckList = $find(this._filterCheckListClientID); // get the check list
//          var column = this._checkListFilterActiveColumn.get_uniqueName(); // get the active column
 
//          filterCheckList.get_items().getItem(0).check(); // check the first item for example
//      }
      function RowCreated(sender, eventArgs) {
          var dataItem = eventArgs.get_gridDataItem();
          for (var i = 0; i < dataItem.get_element().cells.length; i++) {
              dataItem._element.cells[i].onmouseover = function () {
                  this.className = "HoverClass";
              }
              dataItem.get_element().cells[i].onmouseout = function () {
                  var cssName = this.selected ? "ClickClass" : "DefaultClass";
                  this.className = cssName;
                  return;
              }
              dataItem.get_element().cells[i].onclick = function (event) {
                  this.selected = this.selected == true ? false : true;
                  var cssName = this.selected ? "ClickClass" : "DefaultClass";
                  this.className = cssName;
                  return;
              }
          }
      }
  </script>
  <telerik:RadFormDecorator ID="QsfFromDecorator" runat="server" DecoratedControls="All" EnableRoundedCorners="false" />
  <telerik:RadGrid runat="server" ID="RadGrid1" AllowFilteringByColumn="true" FilterType="CheckList" OnNeedDataSource="RadGrid1_NeedDataSource" OnFilterCheckListItemsRequested="RadGrid1_NeedCheckListItems">
    <MasterTableView AutoGenerateColumns="False" >
      <Columns />
    </MasterTableView>
    <ClientSettings>
      <ClientEvents OnRowCreated="RowCreated" />
    </ClientSettings>
  </telerik:RadGrid>

In the code behind Grid's columns are created in the "onLoad" function, while in the "OnNeedDataSource" handler the Grid must be filtered (if client has applied a checklistfilter) and associated to RadGrid1.

.aspx.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Telerik.Web.UI;
 
namespace CheckListFiltering.RadGridWebPart
{
    public partial class RadGridWebPartUserControl : UserControl
    {
        private const int ENABLED = 1;
        private const int DISABLED = 0;
        private const int FILTER = -1;
         
        private static bool Paging;                                          // Paging(true) - Scrolling(false)
        private static DataTable Data = new DataTable();                     // Content of Grid
        private static DataTable DataFiltered;                               // Content of Grid Filtered
        private static String LastFilterExpression;                          // Last value of Filter Expression
        private static int[,] Status;                                        // Auxiliary structure useful to fill FilterCheckList
 
         
        // INITIALIZE SCRIPT MANAGER AND DATA-MEMBERS
 
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager == null)
            {
                scriptManager = new RadScriptManager();
                this.Page.Form.Controls.AddAt(0, scriptManager);
            }
            if (Data.Rows.Count == 0)
            {
                DataSet Ds = new DataSet();
                Ds.ReadXml("C:\\Users\\spadmin\\Documents\\Visual Studio 2010\\Projects\\Telerik\\CheckListFiltering (Webpart)\\CheckListFiltering\\App_Data\\data.xml");  // TODO: Read parameter from a WCF
                Data = Ds.Tables[0];
                Paging = true// TODO: Read parameter from a WCF
                DataFiltered = Data.Select("").Length != 0 ? Data.Select("", Data.Columns[0].ColumnName + " ASC").CopyToDataTable() : new DataTable();
                LastFilterExpression = "";
                Status = new int[Data.Rows.Count, Data.Columns.Count];
                for (int i = 0; i < Data.Rows.Count; i++)
                    for (int j = 0; j < Data.Columns.Count; j++)
                        Status[i, j] = ENABLED;
            }
        }
 
        // INITIALIZE AJAX MANAGER
 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            RadAjaxManager ajaxManager = RadAjaxManager.GetCurrent(this.Page);
            if (ajaxManager == null)
            {
                ajaxManager = new RadAjaxManager();
                ajaxManager.ID = "RadAjaxManager1";
                Controls.Add(ajaxManager);
                this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
            }
        }
 
        // SETTING OF GRID
 
        protected void Page_Load(object sender, EventArgs e)
        {
            RadGrid1.Width = 220 * Data.Columns.Count;
            if (Paging)
            {
                RadGrid1.AllowPaging = true;
                RadGrid1.PagerStyle.AlwaysVisible = true;
            }
            else
            {
                RadGrid1.ClientSettings.Scrolling.AllowScroll = true;
                RadGrid1.ClientSettings.Scrolling.ScrollHeight = 300;
            }
            RadGrid1.MasterTableView.Columns.Clear();
            for (int i = 0; i < Data.Columns.Count; i++)
            {
                GridBoundColumn boundColumn = new GridBoundColumn();
                boundColumn.DataField = Data.Columns[i].ColumnName;
                boundColumn.HeaderText = Data.Columns[i].ColumnName;
                boundColumn.FilterCheckListEnableLoadOnDemand = true;
                boundColumn.FilterDelay = 200;
                RadGrid1.MasterTableView.Columns.Add(boundColumn);
            }
        }
 
        // DATA-FILTERING AND DATA-BINDING
 
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            String filterExpression = Fix_Expression(RadGrid1.MasterTableView.FilterExpression);
            DataFiltered = Data.Select(filterExpression).Length != 0 ? Data.Select(filterExpression, Data.Columns[0].ColumnName + " ASC").CopyToDataTable() : new DataTable();
            Set_Status(filterExpression);
            LastFilterExpression = filterExpression;
            RadGrid1.DataSource = DataFiltered;
        }
 
        // BUILD FILTER-CHECKLIST
 
        public void RadGrid1_NeedCheckListItems(object sender, GridFilterCheckListItemsRequestedEventArgs e)
        {
            e.ListBox.DataKeyField = e.Column.DataField;
            e.ListBox.DataTextField = e.Column.DataField;
            e.ListBox.DataValueField = e.Column.DataField;
            int col_index = Get_Index(e.Column.DataField);
            DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
            for (int i = 0; i < dr.Length; i++)
            {
                RadListBoxItem Item = new RadListBoxItem();
                Item.Text = Convert.ToString(dr[i][col_index]);
                Item.Value = Convert.ToString(dr[i][col_index]);
                Item.Enabled = !Status[i, col_index].Equals(DISABLED) ? true : false;
                Item.Checked = !Status[i, col_index].Equals(FILTER) ? true : false;
                bool Found = false;
                for (int k = 0; k < e.ListBox.Items.Count; k++)
                {
                    if (e.ListBox.Items[k].Text.Equals(Item.Text))
                    {
                        Found = true;
                        break;
                    }
                }
                if (!Found)
                    e.ListBox.Items.Add(Item);
            }
        }
 
        // UTILITY: MANAGE PROPERLY "filterExpression"
 
        public String Fix_Expression(String filterExpression)
        {
            String newExpression = "";
            String[] Expression = filterExpression.Split(new String[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
            for (int k = 0; k < Expression.Length; k++)
            {
                if (Expression[k].Contains("LIKE"))
                    Expression[k] = Expression[k].Replace("'%", "'");
                else
                {
                    DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
                    String col_name = Expression[k].Substring(Expression[k].IndexOf("[") + 1, Expression[k].IndexOf("]") - Expression[k].IndexOf("[") - 1);
                    int col_index = Get_Index(col_name);
                    for (int i = 0; i < Data.Rows.Count; i++)
                    {
                        if (Status[i, col_index].Equals(DISABLED))
                            Expression[k] = Expression[k].Replace(")", " OR [" + col_name + "] = '" + Convert.ToString(dr[i][col_index]) + "')");
                    }
                }
                newExpression = (k != (Expression.Length - 1)) ? newExpression + Expression[k] + " AND " : newExpression + Expression[k];
            }
            return newExpression;
        }
 
        // UTILITY: MODIFY "Status" BASED ON "filterExpression"
 
        public void Set_Status(string filterExpression)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (!filterExpression.Contains(Data.Columns[j].ColumnName))
                {
                    for (int i = 0; i < Data.Rows.Count; i++)
                        Status[i, j] = Status[i, j].Equals(FILTER) ? -2 : Status[i, j];
                }
            }
            String[] Expression = filterExpression.Split(new String[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
            for (int k = 0; k < Expression.Length; k++)
            {
                DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
                String col_name = Expression[k].Substring(Expression[k].IndexOf("[") + 1, Expression[k].IndexOf("]") - Expression[k].IndexOf("[") - 1);
                int col_index = Get_Index(col_name);
                if (Expression[k].Contains("LIKE"))
                {
                    for (int i = 0; i < Data.Rows.Count; i++)
                        Status[i, col_index] = Status[i, col_index].Equals(FILTER) ? -2 : Status[i, col_index];
                }
                else
                {
                    for (int i = 0; i < Data.Rows.Count; i++)
                    {
                        if (Expression[k].Contains(Convert.ToString("'" + dr[i][col_index] + "'")))
                            Status[i, col_index] = Status[i, col_index].Equals(FILTER) ? -2 : Status[i, col_index];
                        else
                            Status[i, col_index] = FILTER;
                    }
                }
            }
            for (int i = 0; i < Data.Rows.Count; i++)
                for (int j = 0; j < Data.Columns.Count; j++)
                {
                    if (!Is_Filtered(i))
                        Status[i, j] = ENABLED;
                    if (Is_Filtered(i) && !Status[i, j].Equals(FILTER))
                        Fix_Element(i, j);
                }
        }
 
        // UTILITY: SUPPORT TO MODIFY "Status"
 
        public void Fix_Element(int row_index, int col_index)
        {
            bool Disabled = true;
            DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
            for (int i = 0; i < dr.Length; i++)
            {
                if (i != row_index && Convert.ToString(dr[i][col_index]).Equals(Convert.ToString(dr[row_index][col_index])) && !Is_Filtered(i))
                {
                    Disabled = false;
                    break;
                }
            }
            Status[row_index, col_index] = Disabled ? DISABLED : ENABLED;
        }
 
        // UTILITY: VERIFY IF A SPECIFIC ROW OF THE GRID IS FILTERED
 
        public bool Is_Filtered(int index)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (Status[index, j].Equals(FILTER))
                    return true;
            }
            return false;
        }
 
        // UTILITY: RETURNS INDEX OF THE COLUMN OF TABLE FROM ITS NAME
 
        public int Get_Index(String name)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (Data.Columns[j].ColumnName.Equals(name))
                    return j;
            }
            return -1;
        }
 
    }
}


So, now that you know what I intend to do, my questions are:

1) As you can see in the handler method for the "OnNeedDataSource" event, when this function is called because a filter is applied by clientside, i always find RadGrid1.MasterTableView.FilterExpression as an empty string; where i can find in the code behind information about the filter that client has applied to the Grid?

2) I well know that by selecting items in the ListBox, the grid will not filtered without clicking the Apply button, this operation must be done by clientside; my purpose is to make filterchecklist provided by telerik as similar as possible to an Excel-like filter: so i use the static member "Status" in the code behind to keep in memory if an  element of the grid must appear enabled, disabled (if an item on the same row has been temporalily deleted by the grid because of a filter that is currently applied) or unchecked (if a filter on this item has been applied) in the checklist returned by "OnFilterCheckListItemsRequested" handler.

I just did a similar project using a webservice (like in your example) to return the checklists to clientside and i saw that, to implement such behaviour, expecially in complex scenarios where more filters are applied, is necessary to manage via javascript the checklist before returning it to clientside.

Now that i need (for other reasons) to create a new project that doesn't use a webservice, i also hoped that by using member Checked of Radlistboxitem i could check/uncheck the items to return to the client also by code behind but it doesn't work.

So in order to manage correctly the listbox i need to save information about filtering in the code behind:

                RadListBoxItem Item = new RadListBoxItem();
                Item.Text =Convert.ToString(Data[row_index][col_index]);
                Item.Value = (Status[row_index][col_index]).Equals("Filtered") ? "FILTER" "NOFILTER";

and retrieve it  on the .aspx:

                filterCheckList.get_items().getItem(i).check();

In the .aspx page, how can i read the member "Value" of an item and, after i've read it, set this member equals to item.text?

3) After you've read my code, any suggest about this matter?

Thanks in advance, 
Regards, Carla

0
Kostadin
Telerik team
answered on 14 Apr 2014, 02:31 PM
Hi Carla,

Straight to your questions.
  1. Note that the filter will be applied on the client only if you are using a client side data-binding. In your case since you are using a server side data-binding the filter will be applied on the server. So basically after apply a filter it will automatically call the NeedDataSource event handler and you could access the filter expression of the MasterTableView. 
    protected void RadGrid2_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        string filterExpreassion = RadGrid2.MasterTableView.FilterExpression;
        //your code
    }
    I attached a small runnable sample where you could check that the filter expression is not empty string after applying some filter.
  2. You could use the approach from my previous reply to get all items. The you could loop through all of them the get the value or the check state of each item. Please check out the following code snippet.
    <script type="text/javascript">
        var count = 0;
        Telerik.Web.UI.RadGrid.prototype._checkListItemsRequestedHandler = function () {
            var items = $find(this._filterCheckListClientID).get_items()
            count = items.get_count();
            for (var i = 0; i < length; i++) {
                var value = items.getItem(i).get_value();
                var checked = items.getItem(i).get_checked();
            }
            debugger;
        }
     
    </script>
  3. I am afraid that none of the provided CSS rules could caused the misalignment of the buttons. Could you please verify that you do not have applied other style to this page. I would recommend you to inspect the input element and check for a width attribute which most probably is causing this issue. Keep in mind that without a isolating project it will be hard to pinpoint the reason for this behavior.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Carla
Top achievements
Rank 1
answered on 16 Apr 2014, 10:36 AM
Hello Kostadin, i have made ​​significant progress with regard to the points i've written: i understood why i wasn't able to intercept the FilterExpression in the code-behind and how to check/uncheck the items in javascript section of the .aspx page.
I have a very important question for my purposes: the webpart containing the RadGrid with filterchecklit that I implemented is displayed correctly with IE8? I'm working with IE9 and it's displayed correctly, setting Browser Mode: IE8 i just see "No records to display"
0
Carla
Top achievements
Rank 1
answered on 16 Apr 2014, 10:37 AM
Regards,
Carla
0
Carla
Top achievements
Rank 1
answered on 16 Apr 2014, 05:03 PM
I'm sorry Kostadin, don't mind about what i wrote in my last post, it works very good also for IE8: finally i'm able to use a customized filter for my grid; there's just a little point i was not able to solve: for IE i still have the problem of button's alignment and also another graphical problem as you can see in the attached file: the double scrollbar.
Can i give to you my isolated project (if the answer is affirmative how can i); however this is a simple sharepoint webpart and i post to you its complete code, latest version (as you can see i'm trying to use the css class .RadFilterMenu_CheckList without success).

my .aspx page:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Telerik.Web.UI, Version=2014.1.403.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI, Version=2014.1.403.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RadGridWebPartUserControl.ascx.cs" Inherits="CheckListFiltering.RadGridWebPart.RadGridWebPartUserControl" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
  <style type="text/css">
  .HoverClass
  
      background-color: aqua;
  }
  .ClickClass
  {
      background-color: yellow;
  }
  .RadFilterMenu_CheckList
  {
      height: 300px;
      width: 200px;
  }
  </style>
  <script type="text/javascript">
      Telerik.Web.UI.RadGrid.prototype._checkListItemsRequestedHandler = function () {
          var items = $find(this._filterCheckListClientID).get_items();
          var count = items.get_count();
          for (var i = 0; i < count; i++) {
              var value = items.getItem(i).get_value().toString();
              if (value != "0")
                  items.getItem(i).check();
              else
                  items.getItem(i).uncheck();
              items.getItem(i).set_value(items.getItem(i).get_text());
          }
      }
      function RowCreated(sender, eventArgs) {
          var dataItem = eventArgs.get_gridDataItem();
          for (var i = 0; i < dataItem.get_element().cells.length; i++) {
              dataItem._element.cells[i].onmouseover = function () {
                  this.className = "HoverClass";
              }
              dataItem.get_element().cells[i].onmouseout = function () {
                  var cssName = this.selected ? "ClickClass" : this.defaultStatus;
                  this.className = cssName;
                  return;
              }
              dataItem.get_element().cells[i].onclick = function (event) {
                  this.selected = this.selected == true ? false : true;
                  var cssName = this.selected ? "ClickClass" : this.defaultStatus;
                  this.className = cssName;
                  return;
              }
          }
      }
  </script>
  <telerik:RadFormDecorator ID="QsfFromDecorator" runat="server" DecoratedControls="All" EnableRoundedCorners="false" />
  <telerik:RadGrid runat="server" ID="RadGrid1" AllowFilteringByColumn="true" FilterType="CheckList" EnableLinqExpressions="false"
                   OnNeedDataSource="RadGrid1_NeedDataSource" OnFilterCheckListItemsRequested="RadGrid1_NeedCheckListItems">
    <MasterTableView AutoGenerateColumns="false">
      <Columns />
    </MasterTableView>
    <ClientSettings>
      <ClientEvents OnRowCreated="RowCreated" />
    </ClientSettings>
  </telerik:RadGrid>

my .aspx.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Telerik.Web.UI;
 
namespace CheckListFiltering.RadGridWebPart
{
    public partial class RadGridWebPartUserControl : UserControl
    {
        private const int VISIBLE = 1;
        private const int FILTER = 0;
        private const int INVISIBLE = -1;
        private const int UNKNOWN = 99;
        
        private static bool Paging;                          // Paging(true) - Scrolling(false)
        private static DataTable Data = new DataTable();     // Contenuto della griglia
        private static DataTable DataFiltered;               // Contenuto della griglia filtrata
        private static int[,] Status;                        // Struttura ausiliaria utile al riempimento delle "FilterCheckList"
 
         
        // Inizializzazione dello "ScriptManager" (ad ogni caricamento della pagina), dei dati membro e della griglia (solo al caricamento iniziale)
 
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager == null)
            {
                scriptManager = new RadScriptManager();
                this.Page.Form.Controls.AddAt(0, scriptManager);
            }           
            if (Data.Rows.Count == 0)
            {
                DataSet Ds = new DataSet();
                Ds.ReadXml("C:\\Temp\\App_Data\\data.xml");  // TODO: Read parameter
                Paging = true;                               // TODO: Read parameter
                Data = Ds.Tables[0];
                DataFiltered = Data.Select("").Length != 0 ? Data.Select("", Data.Columns[0].ColumnName + " ASC").CopyToDataTable() : new DataTable();
                Status = new int[Data.Rows.Count, Data.Columns.Count];
                for (int i = 0; i < Data.Rows.Count; i++)
                    for (int j = 0; j < Data.Columns.Count; j++)
                        Status[i, j] = VISIBLE;               
                RadGrid1.Width = 220 * Data.Columns.Count;
                if (Paging)
                {
                    RadGrid1.AllowPaging = true;
                    RadGrid1.PagerStyle.AlwaysVisible = true;
                }
                else
                {
                    RadGrid1.ClientSettings.Scrolling.AllowScroll = true;
                    RadGrid1.ClientSettings.Scrolling.ScrollHeight = 300;
                }
                for (int i = 0; i < Data.Columns.Count; i++)
                {
                    GridBoundColumn Column = new GridBoundColumn();
                    RadGrid1.MasterTableView.Columns.Add(Column);
                    Column.DataField = Data.Columns[i].ColumnName;
                    Column.UniqueName = Data.Columns[i].ColumnName;
                    Column.HeaderText = Data.Columns[i].ColumnName;
                    Column.FilterDelay = 200;
                    Column.FilterCheckListEnableLoadOnDemand = true;
                }
            }
        }
 
 
        // Filtraggio e databinding della griglia
         
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            String filterExpression = Fix_Expression(RadGrid1.MasterTableView.FilterExpression);
            DataFiltered = Data.Select(filterExpression).Length != 0 ? Data.Select(filterExpression, Data.Columns[0].ColumnName + " ASC").CopyToDataTable() : new DataTable();
            Set_Status(filterExpression);
            RadGrid1.DataSource = DataFiltered;
        }
 
 
        // Creazione delle "FilterCheckList"
         
        public void RadGrid1_NeedCheckListItems(object sender, GridFilterCheckListItemsRequestedEventArgs e)
        {
            int col_index = Get_Index(e.Column.UniqueName);
            DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
            for (int i = 0; i < dr.Length; i++)
            {
                if (!Status[i, col_index].Equals(INVISIBLE))
                {
                    RadListBoxItem Item = new RadListBoxItem();
                    Item.Text = Convert.ToString(dr[i][col_index]);
                    Item.Value = Convert.ToString(Status[i, col_index]);
                    bool Found = false;
                    for (int k = 0; k < e.ListBox.Items.Count; k++)
                    {
                        if (e.ListBox.Items[k].Text.Equals(Item.Text))
                        {
                            Found = true;
                            break;
                        }
                    }
                    if (!Found)
                        e.ListBox.Items.Add(Item);
                }
            }
        }
 
 
        // Utility per la manipolazione della "FilterExpression"
         
        public String Fix_Expression(String filterExpression)
        {
            String newExpression = "";
            for (int i = 0; i < Data.Columns.Count; i++)
            {
                if ( RadGrid1.MasterTableView.Columns[i].EvaluateFilterExpression().Contains("=") )
                {
                    String expression = RadGrid1.MasterTableView.Columns[i].EvaluateFilterExpression();
                    String col_name = expression.Substring(expression.IndexOf("[") + 1, expression.IndexOf("]") - expression.IndexOf("[") - 1);
                    String value = expression.Substring(expression.IndexOf("'") + 1, expression.LastIndexOf("'") - expression.IndexOf("'") - 1);
                    filterExpression = filterExpression + " AND ([" + col_name + "] LIKE '" + value + "%')";
                }
            }
            String[] Expression = filterExpression.Split(new String[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
            for (int k = 0; k < Expression.Length; k++)
            {
                if (Expression[k].Contains("LIKE"))
                    Expression[k] = Expression[k].Replace("'%", "'");
                else
                {
                    DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
                    String col_name = Expression[k].Substring(Expression[k].IndexOf("[") + 1, Expression[k].IndexOf("]") - Expression[k].IndexOf("[") - 1);
                    int col_index = Get_Index(col_name);
                    for (int i = 0; i < Data.Rows.Count; i++)
                    {
                        if (Status[i, col_index].Equals(INVISIBLE))
                            Expression[k] = Expression[k].Remove(Expression[k].LastIndexOf(")")) + " OR ([" + col_name + "] = '" + Convert.ToString(dr[i][col_index]) + "'))";
                    }
                }
                newExpression = (k != (Expression.Length - 1)) ? newExpression + Expression[k] + " AND " : newExpression + Expression[k];
            }
            return newExpression.Replace("||"," OR ");
        }
 
 
        // Utility per la modifica di "Status" sulla base del valore della "FilterExpression"
 
        public void Set_Status(string filterExpression)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (!filterExpression.Contains(Data.Columns[j].ColumnName))
                {
                    for (int i = 0; i < Data.Rows.Count; i++)
                        Status[i, j] = Status[i, j].Equals(FILTER) ? UNKNOWN : Status[i, j];
                }
            }
            String[] Expression = filterExpression.Split(new String[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
            for (int k = 0; k < Expression.Length; k++)
            {
                DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
                String col_name = Expression[k].Substring(Expression[k].IndexOf("[") + 1, Expression[k].IndexOf("]") - Expression[k].IndexOf("[") - 1);
                int col_index = Get_Index(col_name);
                if ( !Expression[k].Contains("LIKE") )
                {
                    for (int i = 0; i < Data.Rows.Count; i++)
                    {
                        if ( Expression[k].Contains(Convert.ToString("'" + dr[i][col_index] + "'")) )
                            Status[i, col_index] = Status[i, col_index].Equals(FILTER) ? UNKNOWN : Status[i, col_index];
                        else
                            Status[i, col_index] = FILTER;
                    }
                }
            }
            for (int i = 0; i < Data.Rows.Count; i++)
                for (int j = 0; j < Data.Columns.Count; j++)
                {
                    if (!Is_Filtered(i))
                        Status[i, j] = VISIBLE;
                    if (Is_Filtered(i) && !Status[i, j].Equals(FILTER))
                        Fix_Element(i, j);
                }
        }
 
 
        // Utility di supporto alla modifica di "Status"
 
        public void Fix_Element(int row_index, int col_index)
        {
            bool Invisible = true;
            DataRow[] dr = Data.Select("", Data.Columns[0].ColumnName + " ASC");
            for (int i = 0; i < dr.Length; i++)
            {
                if (i != row_index && Convert.ToString(dr[i][col_index]).Equals(Convert.ToString(dr[row_index][col_index])) && !Is_Filtered(i))
                {
                    Invisible = false;
                    break;
                }
            }
            Status[row_index, col_index] = Invisible ? INVISIBLE : VISIBLE;
        }
 
 
        // Utility che verifica se una specifica riga della griglia è filtrata o meno
 
        public bool Is_Filtered(int index)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (Status[index, j].Equals(FILTER))
                    return true;
            }
            return false;
        }
 
 
        // Utility che restituisce l'indice di una colonna della tabella a partire dal suo nome
 
        public int Get_Index(String name)
        {
            for (int j = 0; j < Data.Columns.Count; j++)
            {
                if (Data.Columns[j].ColumnName.Equals(name))
                    return j;
            }
            return -1;
        }
 
    }
}


Thanks in advance.
Regards, Carla
0
Kostadin
Telerik team
answered on 17 Apr 2014, 02:38 PM
Hello Carla,

I am afraid that with out a runnable sample or a live url it will be hard to provide you with a proper solution for the button alignment and the double border. Nevertheless you could check the applied css by using a FireBug for FireFox or WebDeveloperTool for IE and see what is causing those issues.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Carla
Top achievements
Rank 1
answered on 17 Apr 2014, 04:54 PM
Kostadin i need it for IE and i just tried with WebDeveloperTool but this didn't help me. Is it possible for you to build a runnable example just copying the code i have posted into a visual webpart? Or can i pass to you a .zip with .sln file (How can i)?

Thanks in Advance.

Regards, Carla. 
0
Kostadin
Telerik team
answered on 22 Apr 2014, 11:29 AM
Hi Carla,

I prepared a small sample based on your code and on my side seems to work properly. Could you please give it a try and let me know how it differs from your real setup?

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
Tags
Grid
Asked by
Carla
Top achievements
Rank 1
Answers by
Kostadin
Telerik team
Carla
Top achievements
Rank 1
Share this question
or