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

RadGrid dynamic creation with ObjectDataSource

2 Answers 197 Views
Grid
This is a migrated thread and some comments may be shown as answers.
alex lexx
Top achievements
Rank 1
alex lexx asked on 03 Feb 2011, 01:29 PM
I'm trying to create a radgrid dynamically and bind it to a dynamically created ObjectDataSource, but grid is always empty (maxRows is 0 in GetData method).  What did I do  wrong?

Next question is this._grid.DataBind() in OnLoad method. Is it necessary? After it grid will show data, but paging will not work (other pages will by empty).

Standard GridView seems to be working correctly.

Here is full sources

using System;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using Parus.Core;
using Telerik.Web.UI;
 
namespace WebDesigner
{
    public partial class WebForm1 : Page
    {
        private RadGrid _grid;
        private GridView _grid2;
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this._grid = CreateGrid();
            this.GridPlaceHolder.Controls.Add(this._grid);
            this._grid2 = CreateGrid2();
            this.GridPlaceHolder.Controls.Add(this._grid2);
        }
 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            RadAjaxManager.AjaxSettings.AddAjaxSetting(this._grid, this._grid);
            RadAjaxManager.AjaxSettings.AddAjaxSetting(this._grid2, this._grid2);
            //_grid.DataBind();
            _grid2.DataBind();
        }
 
        private static RadGrid CreateGrid()
        {
            var grid = new RadGrid
                           {
                               Width = new Unit(100, UnitType.Percentage),
                               ID = "grid_test",
                               Skin = "Windows7",
                               PageSize = 10,
                               AllowPaging = true,
                               AutoGenerateColumns = false,
                               GroupingEnabled = false,
                               ShowGroupPanel = false,
                           };
            grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
            grid.PagerStyle.AlwaysVisible = true;
            grid.NeedDataSource += Grid_NeedDataSource;
 
            grid.MasterTableView.Width = new Unit(100, UnitType.Percentage);
            grid.MasterTableView.PageSize = grid.PageSize;
            grid.MasterTableView.AllowPaging = grid.AllowPaging;
            grid.MasterTableView.PagerStyle.Mode = grid.PagerStyle.Mode;
            grid.MasterTableView.PagerStyle.AlwaysVisible = grid.PagerStyle.AlwaysVisible;
            grid.MasterTableView.AutoGenerateColumns = grid.AutoGenerateColumns;
 
            var gridColumn = new GridBoundColumn();
            gridColumn.DataField = "NRN";
            gridColumn.HeaderText = "Ident";
            grid.MasterTableView.Columns.Add(gridColumn);
 
            gridColumn = new GridBoundColumn();
            gridColumn.DataField = "SCODE";
            gridColumn.HeaderText = "Caption";
            grid.MasterTableView.Columns.Add(gridColumn);
 
            return grid;
        }
 
        private GridView CreateGrid2()
        {
            var grid = new GridView
                           {
                               Width = new Unit(100, UnitType.Percentage),
                               ID = "grid_test2",
                               PageSize = 10,
                               AllowPaging = true,
                               AutoGenerateColumns = false,
                               DataSource = new MyDataSource(typeof(CustomDataProxy))
                           };
 
            grid.PageIndexChanging += Grid2_PageIndexChanging;
 
            var gridColumn = new BoundField();
            gridColumn.DataField = "NRN";
            gridColumn.HeaderText = "Ident";
            grid.Columns.Add(gridColumn);
 
            gridColumn = new BoundField();
            gridColumn.DataField = "SCODE";
            gridColumn.HeaderText = "Caption";
            grid.Columns.Add(gridColumn);
 
            return grid;
 
        }
 
        private void Grid2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this._grid2.PageIndex = e.NewPageIndex;
            this._grid2.DataBind();
        }
 
        private static void Grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var grid = sender as RadGrid;
            grid.DataSource = new MyDataSource(typeof(CustomDataProxy));
        }
    }
 
    #region MyObjectDataSource
 
    [DataObject]
    public class MyDataSource : ObjectDataSource
    {
        public MyDataSource(Type type)
        {
            this.DataProxy = type;
            TypeName = type.FullName;
            SelectCountMethod = "GetTotalRowsCount";
            SelectMethod = "GetData";
            EnablePaging = true;
            MaximumRowsParameterName = "maxRows";
            StartRowIndexParameterName = "firstRow";
            SortParameterName = "orderFields";
            ObjectCreating += OnObjectCreating;
        }
 
        private Type DataProxy
        {
            get;
            set;
        }
 
        private void OnObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = Activator.CreateInstance(DataProxy, new[] { "V_WEBTEST_CODE" });
        }
    }
 
    #endregion
 
    #region Custom DataObject
 
    public class CustomDataProxy : BaseDataProxy
    {
        private readonly string _tableName;
        public CustomDataProxy(string tableName)
        {
            this._tableName = tableName;
        }
 
 
        public override string TableName
        {
            get
            {
                return this._tableName;
            }
        }
    }
 
    [DataObject]
    public abstract class BaseDataProxy
    {
        private const string CCountQuery = "select count(*) from {0}";
        private const string CSelectTemplate = "select * from {0}";
        private const string COrderTemplate = " order by {0}";
        private const string CPagingQuery = "select * from (select rownum rownum#, T.* from ({0}) T) where rownum# between :StartRow and :EndRow";
 
        abstract public string TableName
        {
            get;
        }
 
        public int GetTotalRowsCount()
        {
            using (var connection = Dispatcher.Instance.CreateConnection())
            {
                var queryText = string.Format(CCountQuery, this.TableName);
                using (var query = new OracleCommand(queryText, connection)
                                       {
                                           CommandType = CommandType.Text
                                       })
                {
                    var result = query.ExecuteScalar();
                    return result != null ? Convert.ToInt32(result, CultureInfo.CurrentCulture) : 0;
                }
            }
        }
 
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public DataTable GetData(int firstRow, int maxRows, string orderFields)
        {
            using (var connection = Dispatcher.Instance.CreateConnection())
            {
                var queryText = string.Format(CSelectTemplate, this.TableName);
                if (!string.IsNullOrEmpty(orderFields))
                {
                    queryText += string.Format(COrderTemplate, orderFields);
                }
 
                queryText = string.Format(CPagingQuery, queryText);
 
                var query = new OracleCommand(queryText, connection)
                {
                    CommandType = CommandType.Text
                };
 
                query.Parameters.Add(@"StartRow", firstRow + 1);
                query.Parameters.Add(@"EndRow", firstRow + maxRows);
 
                using (var a = new OracleDataAdapter(query))
                {
                    var dt = new DataTable
                    {
                        Locale = CultureInfo.CurrentCulture
                    };
 
                    a.Fill(dt);
                    return dt;
                }
            }
        }
    }
 
    #endregion
}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebDesigner.WebForm1" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!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">
  <telerik:RadScriptManager ID="RadScriptManager" runat="server">
  </telerik:RadScriptManager>
  <asp:PlaceHolder ID="GridPlaceHolder" runat="server"></asp:PlaceHolder>
  <telerik:RadAjaxManager ID="RadAjaxManager" runat="server">
  </telerik:RadAjaxManager>
  </form>
</body>
</html>

2 Answers, 1 is accepted

Sort by
0
Accepted
Marin
Telerik team
answered on 03 Feb 2011, 03:48 PM
Hello alex,

The problem is in the binding for the grid in the NeedDataSource method:

grid.DataSource = new MyDataSource(typeof(CustomDataProxy));

The DataSource property should be assigned an enumerable collection holding the data, not an instance of the ObjectDataSource. There is another property of the grid - DataSourceID that takes the string ID of the datasource but it is mainly used in markup. You need to refactor your code so that it sets the actual data to the DataSource property in the event. Additionally you can have a look at the following demos showing programmatic creation of RadGrid:
Grid / On PageInit
Creating the grid entirely in the code behind

As for the other question about DataBind method. It is not recommended to explicitly call it if you use the NeedDataSource event to bind the grid. It is not needed in the Page_Load event. If you do want to refresh the grid you should use the grid.Rebind() method.

Regards,
Marin
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
alex lexx
Top achievements
Rank 1
answered on 03 Feb 2011, 04:26 PM
Thanks, but refactoring is not possible ... a very large and complex project, we are trying to change the DevExpress components (there its work) at Telerik =))).
 I will come up with how to get around it. (((
Tags
Grid
Asked by
alex lexx
Top achievements
Rank 1
Answers by
Marin
Telerik team
alex lexx
Top achievements
Rank 1
Share this question
or