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

Simple Grid DataBind

5 Answers 126 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Ricardo
Top achievements
Rank 1
Ricardo asked on 05 Aug 2011, 05:23 PM
Hello people!

I'm trying to follow your simple databind example from : http://www.telerik.com/help/aspnet-ajax/grid-simple-data-binding.html but i have a problem, when the page loads for the first my grind has data, but when i sort, filter or paging, the data disappears and my grind comes at blank.....I'm passing a IList as Datasource My code is :
namespace iConnect.InvoicesScaling.Views
{
    public partial class InvoicesScalingDefault : Microsoft.Practices.CompositeWeb.Web.UI.Page, IInvoicesScale
    {
        private InvoicesScalePresenter _presenter;
  
  
  
        public System.Collections.Generic.IList<Data.SapDocuments> SapDocuments
        {
            get;
            set;
        }
  
  
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
  
                LoadData();
                RadGrid1.DataBind();
            }
            this._presenter.OnViewLoaded();
  
  
            //A cada acesso à pagina verifica quem é o user 
  
            //criar instancia da Info para aceder ao metodo que me vai buscar a lista de users ao AD
            Info x = new Info("xxx", "xxx", "xxxxx,DC=xx,DC=xx");
  
            //get da lista dos direct report em user,key=manager(xx)
            Dictionary<string, string> networkUser = new Dictionary<string, string>();
            networkUser = x.GetHierarchyTree("axxva3");
  
      
            //MessageBox.Show(Page.User.Identity.Name);
  
            ////Popular dados na Radlist 
            //RadGrid1.DataSource = this.SapDocuments;
            //RadGrid1.DataBind();
  
  
        }
  
        [CreateNew]
        public InvoicesScalePresenter Presenter
        {
            set
            {
                this._presenter = value;
                this._presenter.View = this;
            }
        }
  
        private void LoadData()
        {
            ////Popular dados na Radlist 
            RadGrid1.DataSource = this.SapDocuments;
  
  
        }
  
        protected void RadGrid1_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
        {
            RadGrid1.CurrentPageIndex = e.NewPageIndex;
            LoadData();
            RadGrid1.DataBind();
        }
  
  
        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == Telerik.Web.UI.RadGrid.ExportToCsvCommandName)
            {
                RadGrid1.MasterTableView.Columns.FindByUniqueName("SequencialNumber").Visible = false; // hide column before export
  
                RadGrid1.ExportSettings.IgnorePaging = true;
                RadGrid1.DataSource = this.SapDocuments; // please set data source again.
                RadGrid1.DataBind();
  
            }
        }
  
  
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
  
            LoadData();
  
        }
    }
}
  
and my aspx file is:
  
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="content" ContentPlaceHolderID="DefaultContent" runat="Server">
    <script src="../Shared/js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="../Shared/js/jquery.tooltip.js" type="text/javascript"></script>
    <script type="text/javascript" src="../Silverlight.js"></script>
    <style type="text/css">
        .RadGrid_Black .rgFilterBox
        {
            background-color: #454545 !important;
        }
    </style>
  
    <h1 style="text-align: center;">
        Invoices Scale</h1>
    <br />
    <div>
        <telerik:RadGrid ID="RadGrid1" runat="server" 
            GridLines="None" AllowPaging="True" ViewStateMode= "Enabled"
            AllowSorting="True" AutoGenerateColumns="False" Width="97%" enableajax="True"
            CssClass="productsGrid" CellSpacing="0" AllowFilteringByColumn="True"
            ShowFooter="True" Skin="Black" AllowMultiRowSelection="True" 
            onitemcommand="RadGrid1_ItemCommand" 
            onpageindexchanged="RadGrid1_PageIndexChanged" onneeddatasource="RadGrid1_NeedDataSource" 
             >
            <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
            <ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
                <Selecting AllowRowSelect="True" />
            </ClientSettings>
            <MasterTableView GridLines="None" ViewStateMode="Enabled" Width="100%" EnableColumnsViewState="true" CommandItemSettings-ShowExportToCsvButton="True"
                CommandItemSettings-ShowAddNewRecordButton="false" 
                CommandItemDisplay="Top" >
                <Columns>
                    <telerik:GridBoundColumn DataField="SequencialNumber" HeaderText="SequencialNumber"
                        UniqueName="SequencialNumber" SortExpression="SequencialNumber">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Priority" HeaderText="Priority" UniqueName="Priority"
                        FilterControlAltText="Filter Priority column" SortExpression="Priority" DataType="System.Int32">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Process" HeaderText="Staging" UniqueName="Process"
                        SortExpression="Process" FilterControlAltText="Filter Process column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="SupplierCode" HeaderText="SupplierCode" UniqueName="SupplierCode"
                        SortExpression="SupplierCode" FilterControlAltText="Filter SupplierCode column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="MessageStatus" HeaderText="MessageStatus" UniqueName="MessageStatus"
                        SortExpression="MessageStatus" FilterControlAltText="Filter MessageStatus column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="DocumentType" HeaderText="DocumentType" UniqueName="DocumentType"
                        FilterControlAltText="Filter DocumentType column" SortExpression="DocumentType">
                    </telerik:GridBoundColumn>
                    <telerik:GridDateTimeColumn UniqueName="InvoiceCreationDate" DataField="InvoiceCreationDate"
                        HeaderText="InvoiceCreationDate" FilterControlAltText="Filter InvoiceCreationDate column"
                        SortExpression="InvoiceCreationDate">
                        <FilterTemplate>
                            <telerik:RadDatePicker ID="RadDatePicker1" runat="server">
                            </telerik:RadDatePicker>
                        </FilterTemplate>
                    </telerik:GridDateTimeColumn>
                    <%--<telerik:GridBoundColumn DataField="InvoiceCreationDate" DataType="InvoiceCreationDate"
                        FilterControlAltText="Filter InvoiceCreationDate column" HeaderText="InvoiceCreationDate"
                        SortExpression="InvoiceCreationDate" UniqueName="InvoiceCreationDate">
                    </telerik:GridBoundColumn>--%>
                    <telerik:GridBoundColumn DataField="SupplierVatNumber" FilterControlAltText="Filter SupplierVatNumber column"
                        HeaderText="SupplierVatNumber" SortExpression="SupplierVatNumber" UniqueName="SupplierVatNumber">
                    </telerik:GridBoundColumn>
                </Columns>
                <%--<EditFormSettings ColumnNumber="2" CaptionFormatString="Edit details for invoice with SequencialNumber {0}"  
                    CaptionDataField="SequencialNumber">   
                    <FormTableItemStyle Wrap="False"></FormTableItemStyle>  
                    <FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>  
                    <FormMainTableStyle CellSpacing="0" CellPadding="3" Width="100%" />  
                    <FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" CssClass="module"  
                        Height="110px" Width="100%" />  
                    <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>  
                    <FormStyle Width="100%" BackColor="#EEF2EA"></FormStyle>  
                    <EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">   
                    </EditColumn>  
                    <FormTableButtonRowStyle HorizontalAlign="Right" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>  
                </EditFormSettings>--%>
                <ExpandCollapseColumn Visible="False">
                    <HeaderStyle Width="19px"></HeaderStyle>
                </ExpandCollapseColumn>
                <RowIndicatorColumn Visible="False">
                    <HeaderStyle Width="20px" />
                </RowIndicatorColumn>
            </MasterTableView>
            <FilterMenu EnableImageSprites="False">
            </FilterMenu>
            <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
            </HeaderContextMenu>
        </telerik:RadGrid>
<%--        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EscalonamentoFacturasConnectionString %>"
            SelectCommand="SELECT [SequencialNumber], [Priority],[Process], [SupplierCode], [MessageStatus], [DocumentType],[InvoiceCreationDate], [SupplierVatNumber] FROM [SapDocuments]
WHERE [Process] IN ('S','SP');"></asp:SqlDataSource>--%>
    </div>
    <br />
    <br />
    <br />
    <br />
    <br />
</asp:Content>

5 Answers, 1 is accepted

Sort by
0
Accepted
Jayesh Goyani
Top achievements
Rank 2
answered on 06 Aug 2011, 10:41 AM
Hello Ricardo,

namespace iConnect.InvoicesScaling.Views
{
    public partial class InvoicesScalingDefault : Microsoft.Practices.CompositeWeb.Web.UI.Page, IInvoicesScale
    {
        private InvoicesScalePresenter _presenter;
         
        public System.Collections.Generic.IList<Data.SapDocuments> SapDocuments
        {
            get;
            set;
        }
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
            }
            this._presenter.OnViewLoaded();
    
    
            //A cada acesso à pagina verifica quem é o user
    
            //criar instancia da Info para aceder ao metodo que me vai buscar a lista de users ao AD
            Info x = new Info("xxx", "xxx", "xxxxx,DC=xx,DC=xx");
    
            //get da lista dos direct report em user,key=manager(xx)
            Dictionary<string, string> networkUser = new Dictionary<string, string>();
            networkUser = x.GetHierarchyTree("axxva3");
    
        
            //MessageBox.Show(Page.User.Identity.Name);
    
            ////Popular dados na Radlist
            //RadGrid1.DataSource = this.SapDocuments;
            //RadGrid1.DataBind();
    
    
        }
    
        [CreateNew]
        public InvoicesScalePresenter Presenter
        {
            set
            {
                this._presenter = value;
                this._presenter.View = this;
            }
        }
    
        private void LoadData()
        {
            ////Popular dados na Radlist
            RadGrid1.DataSource = this.SapDocuments;
    
    
        }
                    
                      // not needed to handle  this event maully if you want this then set customepagging="true"
        //protected void RadGrid1_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
        //{
            //RadGrid1.CurrentPageIndex = e.NewPageIndex;
        //}
    
    
        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == Telerik.Web.UI.RadGrid.ExportToCsvCommandName)
            {
                RadGrid1.MasterTableView.Columns.FindByUniqueName("SequencialNumber").Visible = false; // hide column before export
    
                RadGrid1.ExportSettings.IgnorePaging = true;
    
            }
        }
    
    
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
    
            LoadData();
    
        }
    }
}

Radgrid handle sorting and pagging automatically so not need to overwrite except if you set custompagging="true"

Let me know if any concern.

Thanks,
Jayesh Goyani
0
Accepted
Princy
Top achievements
Rank 2
answered on 08 Aug 2011, 05:13 AM
Hello Ricardo,

In order to implement advanced features like paging, sorting etc you should use Advanced DataBinding with NeedDataSource event. Check the following help documentation which explains more about this.
Advanced Data-binding (using NeedDataSource event).

Thanks,
Princy.
0
Ricardo
Top achievements
Rank 1
answered on 08 Aug 2011, 09:38 AM
Hello!!

I tried your code but the problems remains....whane I click to change page or to sort....the grid comes without data....

I set ViewStateMode enabled but nothing change...

Can you please Help me....?
 
namespace iConnect.InvoicesScaling.Views
{
    public partial class InvoicesScalingDefault : Microsoft.Practices.CompositeWeb.Web.UI.Page, IInvoicesScale
    {
        private InvoicesScalePresenter _presenter;
  
  
  
        public System.Collections.Generic.IList<Data.SapDocuments> SapDocuments
        {
            get;
            set;
        }
  
  
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
            }
            this._presenter.OnViewLoaded();
  
  
            //A cada acesso à pagina verifica quem é o user 
  
            //criar instancia da Info para aceder ao metodo que me vai buscar a lista de users ao AD
            Info x = new Info("xxx", "xx", "xxx,DC=xx,DC=xx");
  
            //get da lista dos direct report em user,key=manager(xx)
            Dictionary<string, string> networkUser = new Dictionary<string, string>();
            networkUser = x.GetHierarchyTree("xx"); //xx
  
  
            //string userLogin = Page.User.Identity.Name;
  
            //MessageBox.Show(Page.User.Identity.Name);
  
            ////Popular dados na Radlist 
            //RadGrid1.DataSource = this.SapDocuments;
            //RadGrid1.DataBind();
  
  
        }
  
        [CreateNew]
        public InvoicesScalePresenter Presenter
        {
            set
            {
                this._presenter = value;
                this._presenter.View = this;
            }
        }
  
  
  
        private void LoadData()
        {
            ////Popular dados na Radlist
            RadGrid1.DataSource = this.SapDocuments;
  
        }
  
  
        // not needed to handle  this event maully if you want this then set customepagging="true"
        //protected void RadGrid1_PageIndexChanged(object source, Telerik.Web.UI.GridPageChangedEventArgs e)
        //{
        //RadGrid1.CurrentPageIndex = e.NewPageIndex;
  
        //}
  
  
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
  
            LoadData();
  
        }
  
  
  
        /// <summary>
        /// Export de todos os SequencialNumber da tabela para .csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == Telerik.Web.UI.RadGrid.ExportToCsvCommandName)
            {
                RadGrid1.MasterTableView.Columns.FindByUniqueName("SequencialNumber").Visible = true;
                RadGrid1.ExportSettings.IgnorePaging = true;
  
                int count = 0;
                foreach (GridColumn column in RadGrid1.Columns)
                {
                    if (column.Visible)
                    {
                        if (count > 0)
                            column.Visible = false;
                        else
                            count++;
                    }
                }
  
            }
        }
  
        /// <summary>
        /// Método para formatar o sequencialNumber
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid1_GridExporting(object sender, GridExportingArgs e)
        {
            e.ExportOutput = e.ExportOutput.Replace("\"\r\n\"", "\"\r\n\"'");
        }
  
  
  
  
    }
}
  
  
ASPX FILE:
  
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InvoincesScale.aspx.cs" Inherits="iConnect.InvoicesScaling.Views.InvoicesScalingDefault"
    Title="Invoices Scale" MasterPageFile="~/Shared/Silver.master" %>
  
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="content" ContentPlaceHolderID="DefaultContent" runat="Server">
    <script src="../Shared/js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="../Shared/js/jquery.tooltip.js" type="text/javascript"></script>
    <script type="text/javascript" src="../Silverlight.js"></script>
    <style type="text/css">
        .RadGrid_Black .rgFilterBox
        {
            background-color: #454545 !important;
        }
    </style>
    <h1 style="text-align: center;">
        Invoices Scale</h1>
    <br />
    <div>
        <telerik:RadGrid ID="RadGrid1" runat="server" GridLines="None" AllowPaging="True"
             AllowSorting="True" AutoGenerateColumns="False" ViewStateMode = "Enabled"
            Width="97%" enableajax="True" CssClass="productsGrid" CellSpacing="0" AllowFilteringByColumn="True"
            ShowFooter="True" Skin="Black" AllowMultiRowSelection="True" 
            OnItemCommand="RadGrid1_ItemCommand" 
            ongridexporting="RadGrid1_GridExporting" 
            onneeddatasource="RadGrid1_NeedDataSource">
            <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
            <ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
                <Selecting AllowRowSelect="True" />
            </ClientSettings>
            <MasterTableView GridLines="None" Width="100%" ViewStateMode = "Enabled" 
                CommandItemSettings-ShowExportToCsvButton="True" CommandItemSettings-ShowAddNewRecordButton="false"
                CommandItemDisplay="Top">
                <Columns>
                    <telerik:GridBoundColumn DataField="SequencialNumber" HeaderText="SequencialNumber"
                        UniqueName="SequencialNumber" SortExpression="SequencialNumber">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Priority" HeaderText="Priority" UniqueName="Priority"
                        FilterControlAltText="Filter Priority column" SortExpression="Priority" DataType="System.Int32">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Process" HeaderText="Staging" UniqueName="Process"
                        SortExpression="Process" FilterControlAltText="Filter Process column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="SupplierCode" HeaderText="SupplierCode" UniqueName="SupplierCode"
                        SortExpression="SupplierCode" FilterControlAltText="Filter SupplierCode column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="MessageStatus" HeaderText="MessageStatus" UniqueName="MessageStatus"
                        SortExpression="MessageStatus" FilterControlAltText="Filter MessageStatus column">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="DocumentType" HeaderText="DocumentType" UniqueName="DocumentType"
                        FilterControlAltText="Filter DocumentType column" SortExpression="DocumentType">
                    </telerik:GridBoundColumn>
                    <telerik:GridDateTimeColumn UniqueName="InvoiceCreationDate" DataField="InvoiceCreationDate"
                        HeaderText="InvoiceCreationDate" FilterControlAltText="Filter InvoiceCreationDate column"
                        SortExpression="InvoiceCreationDate">
                        <FilterTemplate>
                            <telerik:RadDatePicker ID="RadDatePicker1" runat="server">
                            </telerik:RadDatePicker>
                        </FilterTemplate>
                    </telerik:GridDateTimeColumn>
                    <%--<telerik:GridBoundColumn DataField="InvoiceCreationDate" DataType="InvoiceCreationDate"
                        FilterControlAltText="Filter InvoiceCreationDate column" HeaderText="InvoiceCreationDate"
                        SortExpression="InvoiceCreationDate" UniqueName="InvoiceCreationDate">
                    </telerik:GridBoundColumn>--%>
                    <telerik:GridBoundColumn DataField="SupplierVatNumber" FilterControlAltText="Filter SupplierVatNumber column"
                        HeaderText="SupplierVatNumber" SortExpression="SupplierVatNumber" UniqueName="SupplierVatNumber">
                    </telerik:GridBoundColumn>
                </Columns>
                <%--<EditFormSettings ColumnNumber="2" CaptionFormatString="Edit details for invoice with SequencialNumber {0}"  
                    CaptionDataField="SequencialNumber">   
                    <FormTableItemStyle Wrap="False"></FormTableItemStyle>  
                    <FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>  
                    <FormMainTableStyle CellSpacing="0" CellPadding="3" Width="100%" />  
                    <FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" CssClass="module"  
                        Height="110px" Width="100%" />  
                    <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>  
                    <FormStyle Width="100%" BackColor="#EEF2EA"></FormStyle>  
                    <EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">   
                    </EditColumn>  
                    <FormTableButtonRowStyle HorizontalAlign="Right" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>  
                </EditFormSettings>--%>
                <ExpandCollapseColumn Visible="False">
                    <HeaderStyle Width="19px"></HeaderStyle>
                </ExpandCollapseColumn>
                <RowIndicatorColumn Visible="False">
                    <HeaderStyle Width="20px" />
                </RowIndicatorColumn>
            </MasterTableView>
            <FilterMenu EnableImageSprites="False">
            </FilterMenu>
            <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
            </HeaderContextMenu>
        </telerik:RadGrid>
x
    </div>
    <br />
    <br />
    <br />
    <br />
    <br />
</asp:Content>
0
Ricardo
Top achievements
Rank 1
answered on 08 Aug 2011, 09:51 AM
Hello,

After i run with Debug I find that after a sort click or a page change or if i use a filter the when I call another time the LoadData(),
my datasource this.SapDocuments comes null.....
0
Ricardo
Top achievements
Rank 1
answered on 08 Aug 2011, 10:12 AM
I found the solution....

I need to call the method to databind my datasource inside the Load() and call it every time..
I'm i correct??
private void LoadData()
        {
            //Popular dados na Radlist
  
            SapDocumentsBO sapDocs = new SapDocumentsBO();
            this.SapDocuments = sapDocs.GetSapDocuments();
  
            RadGrid1.DataSource = this.SapDocuments;
  
  
        }
Tags
General Discussions
Asked by
Ricardo
Top achievements
Rank 1
Answers by
Jayesh Goyani
Top achievements
Rank 2
Princy
Top achievements
Rank 2
Ricardo
Top achievements
Rank 1
Share this question
or