Search code examples
c#asp.nettelerikradgrid

How to add Cell Formatting event method to dynamically created radgrid code behind?


I have created a rad grid on code behind. Now I want to add cell formatting event to it. How can I achieve this?

       RadGrid grid = new RadGrid();
        grid.ID = "rdggrid";

        grid.Skin = "Metro";
        grid.Width = Unit.Percentage(100);            
        grid.PageSize = 15;
        grid.AllowPaging = true;
        grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
        grid.AutoGenerateColumns = false;          


        grid.MasterTableView.Width = Unit.Percentage(100);

        grid.ClientSettings.Resizing.AllowColumnResize = true;
        grid.ClientSettings.Resizing.ResizeGridOnColumnResize = true;
        grid.ClientSettings.Resizing.AllowResizeToFit = true;

        grid.ItemDataBound += new GridItemEventHandler(RadGrid_ItemDataBound);

I want to add this method

void radGrid_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)     
{     

}

Solution

  • In difference with RadGridView for WinForms, RadGrid for ASP.NET AJAX (WebForms) does not offer a CellFormatting server-side event. You can use the ItemDataBound event of RadGrid for ASP.NET AJAX to style the cells:

     protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                if (Convert.ToInt32(((DataRowView)item.DataItem)["Column"]) < value)
                {
                    TableCell cell = item["Column"];
                    cell.BackColor = Color.PeachPuff;
                }
            }
        }
    

    or

    protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            foreach (GridDataItem dataItem in RadGridProduct.MasterTableView.Items)
            {
                int cellCount = dataItem.Cells.Count;
    
                foreach (GridTableCell item in dataItem.Cells)
                {
                    if (item.Text == null ||Convert.ToInt32(item.Text) < 0 )
                        item.BackColor = System.Drawing.Color.Brown;
                }
    
            }
    
        }