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

Change CheckBox to RadioButton in RadGrid

14 Answers 161 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jim
Top achievements
Rank 1
Jim asked on 29 Jun 2013, 01:08 AM
How may I change CheckBox to RadioButton in RadGrid from code behind? Due to the application needs, we didn't use smarttag or markup in .aspx page, but declare RadGrid from Page_Load instead. Is there a attribute of RadGrid that I can define to change CheckBox to RadioButton?

p.s. my version is 2012.2.912.40 

thank you,
Jim

14 Answers, 1 is accepted

Sort by
0
A2H
Top achievements
Rank 1
answered on 30 Jun 2013, 01:45 PM
Hi Jim,

You can use Grid Template column for adding radiobutton to Telerik grid dynamically.

Please use the below code

1)     Declare a control template class in which we will define our Radio Button and its properties.

private class ControlTemplate : ITemplate

     {

         protected RadioButton rdoButton;

         public void InstantiateIn(System.Web.UI.Control container)

         {

             rdoButton = new RadioButton();

             rdoButton.ID = "TestValue";

             rdoButton.Enabled = true;

             container.Controls.Add(rdoButton);

         }

     }

2)     Add the Grid Template column dynamically using the below code. The below code will internally refer the control template class and it will add Radio button to your grid

Protected void Page_Load(object sender, EventArgs e)

    {

        RadGrid RadGrid1 = new RadGrid();

        RadGrid1.ID = "RadGrid1";

                     

        if (!IsPostBack)

        {

            string templateColumnName = "TestName";

            GridTemplateColumn templateColumn = new GridTemplateColumn();

            templateColumn.ItemTemplate = new ControlTemplate();

            templateColumn.HeaderText = templateColumnName;

            RadGrid1.MasterTableView.Columns.Add(templateColumn);

        }

    }


Thanks,
A2H

0
Princy
Top achievements
Rank 1
answered on 01 Jul 2013, 12:24 PM
Hi Jim,

I guess you want the checkbox to act like the radiobutton.
Please try the following link on Single RadioButton check at a time with row selection

Thanks,
Princy
0
Jim
Top achievements
Rank 1
answered on 03 Jul 2013, 04:43 PM
Hi A2H,

thanks for the reply. The code you post make sense to me, however, I still can't see the radio button showing on the page (it's in viewsource).

If you don't mind, please let me know how I can send my code to you via email.

Thanks,
Jim
0
Jim
Top achievements
Rank 1
answered on 03 Jul 2013, 05:20 PM
Hi Princy,

I just went through the thread without implementing the code. A couple things show up to make me feel my situation might be different:

1. In our code we declare radgrid in code behind since we need multiple grids on a page. I tried A2H 's approach and the radio button control shows up in viewsource, however other javascript was dictating what is showing...I am in progress of looking for the code on that.

2. The checkboxes in our datagrid did function like a radio button, but they look like check box hence not a intuitive user experience. I am assuming I don't have to worry about radiobutton grouping....or do I?

Thanks for your reply, and once I figure out the question above, I will mark the replies help me solve my issue as answers.

Thanks,
Jim
0
A2H
Top achievements
Rank 1
answered on 04 Jul 2013, 03:33 AM
Hi Jim,

Is it possible for you to attach a small sample application in this thread.I can take a look into that and help you to resolve the issue.

Thanks,
A2H
0
Kostadin
Telerik team
answered on 04 Jul 2013, 06:41 AM
Hello Jim,

A possible solution is to create a template column as A2H's suggested and add a RadioButton and CheckBox controls in it.Then you could control which of the both controls to be visible by setting display:none to the other one.

Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Jim
Top achievements
Rank 1
answered on 10 Jul 2013, 04:42 PM
Hi A2H,

I am unsure about posting the whole solution yet creating a small solution with similar codes present some challenge to me.

Would you mind reading my partial view control that use Telerik grid view first?

Thanks,
Jim

namespace SETriageWeb.Controls
{
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
    using System.Text;
    using Telerik.Web.UI;
   
 
    public class Grid
    {
        /// <summary>
        /// Gets or sets the title
        /// </summary>
        public string Title
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the default sort by field
        /// </summary>
        public string DefaultSortByField
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the default sort order
        /// </summary>
        public GridSortOrder DefaultSortOrder
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the Data Source to bind the grid to
        /// </summary>
        public object DataSource
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the columns to display from the default data source
        /// </summary>
        public List<string> VisibleColumns
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the default minimum width
        /// </summary>
        public int DefaultWidth
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets a value to turn on paging
        /// </summary>
        public bool AllowPaging
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the default page size if paging is turned on
        /// </summary>
        public int DefaultPageSize
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the link text field
        /// </summary>
        public string LinkTextField
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the link navigation url
        /// </summary>
        public string LinkNavigationUrl
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the link navigation field
        /// </summary>
        public string[] LinkNavigationField
        {
            get;
            set;
        }
 
        /// <summary>
        /// Hide the default client select column from the grid
        /// </summary>
        public bool HideSelectColumn
        {
            get;
            set;
        }
 
        public RadGrid RadGrid
        {
            get;
            set;
        }
    }
    public partial class GridWithMenu : System.Web.UI.UserControl
    {
 
        public int NumberOfGrids
        {
            get
            {
                return this.Grids == null ? 0 : this.Grids.Length;
            }
            set
            {
                this.Grids = new Grid[value];
 
                for (int i = 0; i < value; i++)
                {
                    this.Grids[i] = new Grid();
                    this.Grids[i].RadGrid = new RadGrid();
                    this.Grids[i].RadGrid.ID = string.Format("RadGrid{0}", i);
                }
            }
        }
 
        public Grid[] Grids
        {
            get;
            private set;
        }
 
        /// <summary>
        /// Gets or sets the menu items.
        /// Key is the display name and value is the Navigate URL if any.
        /// If no navigate url is specified, the event has to be handled client side on individual pages
        /// </summary>
        public Dictionary<string, string> MenuItems
        {
            get;
            set;
        }
 
        /// <summary>
        /// Gets or sets the menu action that should be triggered when a row
        /// is double clicked
        /// </summary>
        public string DoubleClickActionMenu
        {
            get;
            set;
        }
 
        /// <summary>
        /// Define a public event to raise the databound event
        /// </summary>
        public event GridItemEventHandler OnItemDataBound;
 
        protected void Page_Init(object source, EventArgs e)
        {
        }
 
        ////attempt to add Radiobutton
        //private class ControlTemplate : ITemplate
        //{
        //    protected RadioButton rdoButton;
        //    public void InstantiateIn(System.Web.UI.Control container)
        //    {
        //        rdoButton = new RadioButton();
        //        rdoButton.ID = "TestValue";
        //        rdoButton.Enabled = true;
        //        container.Controls.Add(rdoButton);
        //    }
        //}
 
        /// <summary>
        /// Handle page load
        /// </summary>
        /// <param name="sender">Page object</param>
        /// <param name="e">Event arguments</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < this.Grids.Length; i++)
            {
                Grid grid = this.Grids[i];
                RadGrid radGrid = grid.RadGrid;
 
 
                
                radGrid.AllowMultiRowSelection = false;
                radGrid.AllowSorting = true;
                radGrid.Skin = "Metro";
                radGrid.EnableEmbeddedSkins = false;
                radGrid.GridLines = GridLines.None;
                radGrid.NeedDataSource += GridNeedDataSource;
                radGrid.HeaderStyle.Wrap = false;
                radGrid.MasterTableView.Columns.Add(new GridClientSelectColumn() { UniqueName = "ClientSelectColumn" });
                radGrid.ClientSettings.EnableRowHoverStyle = true;
                radGrid.ClientSettings.ClientEvents.OnMasterTableViewCreated = "HideMenu";
                radGrid.ClientSettings.ClientEvents.OnRowContextMenu = "RowContextMenu";
                radGrid.ClientSettings.ClientEvents.OnRowSelected = "RowSelected";
                radGrid.ClientSettings.ClientEvents.OnRowDblClick = "RowDblClick";
                radGrid.ClientSettings.Selecting.AllowRowSelect = true;
 
                radGrid.AllowPaging = true;
                radGrid.PageSize = 20;
 
                if (!this.IsPostBack)
                {
                    // Set the Grid Sort
                    if (!string.IsNullOrEmpty(grid.DefaultSortByField))
                    {
                        GridSortExpression sortExpr = new GridSortExpression();
                        sortExpr.FieldName = grid.DefaultSortByField;
 
                        if (this.Grids[i].DefaultSortOrder != 0)
                        {
                            sortExpr.SortOrder = grid.DefaultSortOrder;
                        }
 
                        radGrid.MasterTableView.SortExpressions.AddSortExpression(sortExpr);
                    }
 
                    if (this.Grids[i].DefaultWidth != 0)
                    {
                        radGrid.Width = grid.DefaultWidth;
                    }
 
              
                    if (this.Grids[i].HideSelectColumn)
                    {
                        radGrid.Columns.Remove(grid.RadGrid.Columns[0]);
                    }
 
                    ////attempt to add Radiobutton
                    //string templateColumnName = "TestName";
                    //GridTemplateColumn templateColumn = new GridTemplateColumn();
                    //templateColumn.ItemTemplate = new ControlTemplate();
                    //templateColumn.HeaderText = templateColumnName;
                    //radGrid.MasterTableView.Columns.Add(templateColumn);
                }
 
                if (!String.IsNullOrEmpty(this.Grids[i].Title))
                {
                    Label label = new Label();
                    label.Text = string.Format("<div id='gridtitle'>{0}</div>", this.Grids[i].Title);
 
                    this.RadGrids.Controls.Add(label);
                }
                 
                this.RadGrids.Controls.Add(radGrid);
 
                this.RadGrids.Controls.Add(new Label() { Text = "<br /><br />" });
            }
 
            StringBuilder sb = new StringBuilder();
            sb.Append("var radGridIDs = [");
            for (int i = 0; i < this.Grids.Length; i++)
            {
                sb.AppendFormat("'{0}',", this.Grids[i].RadGrid.ClientID);
            }
            sb.Append("];");
 
            //Utils.AddJavascript(this.RadGrids, sb.ToString());
 
            if (!this.IsPostBack)
            {
                // Load the menu Items
                this.LoadMenuItems(MainMenu);
                this.LoadMenuItems(ContextMenu);
            }
        }
 
 
        /// <summary>
        /// Data bind the grind
        /// </summary>
        /// <param name="sender">Source of the event</param>
        /// <param name="e">Event Arguments</param>
        protected void GridNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            RadGrid radGrid = sender as RadGrid;
            Grid grid = this.FindGrid(radGrid);
 
            radGrid.DataSource = grid.DataSource;
            radGrid.DataBound += new EventHandler(this.RadGrid_DataBound);
            radGrid.ItemDataBound += new GridItemEventHandler(this.RadGrid_ItemDataBound);
        }
 
 
        /// <summary>
        /// Handle the Item Data bound error
        /// </summary>
        /// <param name="sender">Source of the event</param>
        /// <param name="e">Event Arguments</param>
        protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (OnItemDataBound != null)
            {
                OnItemDataBound(sender, e);
            }
        }
 
        /// <summary>
        /// Handle data bound event.
        /// Hide the columns that we don't want to show.
        /// Add the summary row
        /// </summary>
        /// <param name="sender">Source of the event</param>
        /// <param name="e">Event Arguments</param>
        protected void RadGrid_DataBound(object sender, EventArgs e)
        {
            RadGrid radGrid = sender as RadGrid;
            Grid grid = this.FindGrid(radGrid);
            List<string> internalVisibleColumns = new List<string>() { "ClientSelectColumn" };
 
            if (grid.VisibleColumns != null)
            {
                foreach (GridColumn column in radGrid.MasterTableView.RenderColumns.Where(
                    c =>
                        !internalVisibleColumns.Contains(c.UniqueName, StringComparer.OrdinalIgnoreCase) &&
                        !grid.VisibleColumns.Contains(c.UniqueName, StringComparer.OrdinalIgnoreCase)))
                {
                    column.Display = false;
                }
            }
 
            // Workaround to hide the extra columns that the grid seems to add or sort postback
            foreach (GridColumn column in radGrid.MasterTableView.RenderColumns.Where(c => string.IsNullOrWhiteSpace(c.HeaderText) && c.ColumnType == "GridHyperLinkColumn"))
            {
                column.Visible = false;
            }
        }
 
        private Grid FindGrid(RadGrid radGrid)
        {
            foreach (Grid grid in this.Grids)
            {
                if (grid.RadGrid == radGrid)
                {
                    return grid;
                }
            }
            return null;
        }
 
        /// <summary>
        /// Load menu Items
        /// </summary>
        /// <param name="menu">The menu to add items to</param>
        private void LoadMenuItems(RadMenu menu)
        {
            if (this.MenuItems != null)
            {
                foreach (string menuText in this.MenuItems.Keys)
                {
                    RadMenuItem menuItem = new RadMenuItem();
                    menuItem.Text = menuText;
                    if (!string.IsNullOrEmpty(this.MenuItems[menuText]))
                    {
                        menuItem.NavigateUrl = this.MenuItems[menuText];
                    }
 
                    menu.Items.Add(menuItem);
                }
 
                if (menu == MainMenu)
                {
                    menu.Items.Add(new RadMenuItem() { Text = " " });
                }
            }
        }
    }
}
0
Kostadin
Telerik team
answered on 15 Jul 2013, 11:59 AM
Hi Jim,

I would recommend you to review the following help article. Note that if you are using TemplateColumn and you are creating your grid programmatically you have to build it on PageInit event handler.

Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Jim
Top achievements
Rank 1
answered on 11 Sep 2013, 06:27 PM
Hi all,

Right now I adapt Princy's solution with some modification for my dynamic created grid, along with other thread contributors' suggestion. I have radio buttons in the grid. However, right now the selection of the Row is separate from Radio button checked. I have the relevant functions below, and my goal is to make sure that by selecting the row, radiobutton get checked, and vice versa. 

Any suggestion/help would be greatly appreciated.
Jim

This is where RadioButton bound to SelectMeOnly javascript method.

     protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (OnItemDataBound != null)
            {
                OnItemDataBound(sender, e);
            }
            if (e.Item is GridDataItem)
            {


                GridDataItem item = (GridDataItem)e.Item;

                item["ClientSelectColumn"].Controls.RemoveAt(0);

                item["ClientSelectColumn"].Controls.Add(new RadioButton());
                item["ClientSelectColumn"].Controls[0].ID = "rdSelect";

                //chkbx.AutoPostBack =true;

                ((RadioButton)(item["ClientSelectColumn"].Controls[0])).Attributes.Add(

                "OnClick", "SelectMeOnly(" + item["ClientSelectColumn"].Controls[0].ClientID + "," + item.OwnerGridID + ","+e+" )");

            }
       
        } 

And this is the setting in Page_Load calling "RowSelected" method in javascript.

...
radGrid.ClientSettings.ClientEvents.OnRowSelected = "RowSelected";
...


And RowSelected function:

function RowSelected(sender, eventArgs) {
            for (var i in radGridIDs) {
                var radGrid = $find(radGridIDs[i]);
                if (radGrid != sender) {
                    radGrid.get_masterTableView().clearSelectedItems();
                }
            }
           
            var grid = sender;
            var masterTable = grid.get_masterTableView();
            var row = masterTable.get_selectedItems()[0];
         
            $currentRowIndex = eventArgs.get_gridDataItem().get_element().rowIndex;
         
            var gridIndex = sender.ClientID.substr(sender.ClientID.indexOf("RadGrid") + 7);

            UpdateMenus(gridIndex);

            if (typeof (window.ExpandRow) == "function") {
                ExpandRow($('#' + row.get_id()));
            }
        }
0
Kostadin
Telerik team
answered on 16 Sep 2013, 08:59 AM
Hi Jim,

I prepared a small sample and attached it to this post. Basically the previously selected item is removed on every radio button click or row click.

Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Jim
Top achievements
Rank 1
answered on 27 Sep 2013, 10:08 PM
Hi Kostadin,

Thank you for your solution. This is the closest I have been to my goal is. I tweak a little bit in the javascript functions to fit our dynamic generated grid:

 function RowClick(sender, args) {
            RemoveCurrentSelectedItems(sender.ClientID);

            args.get_item().get_cell("ClientSelectColumn").getElementsByTagName('input')[0].checked = true;
            
            var gridIndex = sender.ClientID.substr(sender.ClientID.indexOf("RadGrid") + 7);
            UpdateMenus(gridIndex);
            
        }

        function RadioButtonClick(sender, index, gridId) {
            RemoveCurrentSelectedItems(gridId);
            var g = $find(gridId);
            g.get_masterTableView().get_dataItems()[index].set_selected(true);

            var gridIndex = gridId.substr(gridId.indexOf("RadGrid") + 7);
 
            UpdateMenus(gridIndex);

        }

        function RemoveCurrentSelectedItems(grid) {
            var g = $find(grid);
            var masterTableView = g.get_masterTableView();
            for (var i = 0; i < masterTableView.get_selectedItems().length; i++) {
                var selItem = masterTableView.get_selectedItems()[i];
                var radiobtn = selItem.get_cell("ClientSelectColumn");
     
                radiobtn.getElementsByTagName('input')[0].checked = false;
                alert(radiobtn.getElementsByTagName('input')[0].checked);
                selItem.set_selected(false);
            }
        }


Now, what's odd is, if user click on the radiobutton ( radiobutton is "checked") and click again (radiobutton is unchecked), you will not be able to click on the radiobutton to make it check anymore. User would have to click on somewhere else (if you click on the row, the radiobutton will be checked, but not directly on the radiobutton) to mitigate this issue. This was obviously not acceptable, yet I am struggle to find the "Checked" attribute despite the attribute belong to radiobutton control. 

Does this make sense? I'd be appreciate if you can point me to somewhere I may overlook.

Thanks,
Jim
0
Kostadin
Telerik team
answered on 02 Oct 2013, 12:37 PM
Hello,

A possible solution is to save the previously checked radio button into a variable and execute the logic of the RadioButtonClick function only when it differs from the current checked radio button. Please check out the following code snippet.
var previouslySelectedIndex;
function RadioButtonClick(sender, index) {
    debugger;
    if (previouslySelectedIndex == null || previouslySelectedIndex != index) {
        RemoveCurrentSelectedItems();
        $find("<%= RadGrid1.ClientID %>").get_masterTableView().get_dataItems()[index].set_selected(true);
        previouslySelectedIndex = index;
    }
}


Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Jim
Top achievements
Rank 1
answered on 16 Oct 2013, 04:27 PM
Thanks for your answer, Kostadin. I resolve this issue.

However, a new issue has emerged. Since I have multiple grids on one page, each of the grid can have their own radiobutton selected. I was able to use jquery to updated the radiobutton name (that concatenate with Grid name) to group them, yet the row that were selected won't "de-select" when I select or click other row in other grid. How do I de-select the row when row in other grids were selected? 

Please advise, 

Jim



0
Kostadin
Telerik team
answered on 21 Oct 2013, 12:13 PM
Hello Jim,

You a possible solution is to save not only the previously selected item bu also to save and the grid's id of the item. This way you could deselect the item from this grid.

Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
Tags
Grid
Asked by
Jim
Top achievements
Rank 1
Answers by
A2H
Top achievements
Rank 1
Princy
Top achievements
Rank 1
Jim
Top achievements
Rank 1
Kostadin
Telerik team
Share this question
or