ASP.NET Gridview load data
-
Hi all, where in the lifecycle of an asp.net page do you load the data for a gridview? In Page_Load (which runs twice and check on !IsPostback is needed), in Page_LoadComplete (runs once) or in Page_Prerender (runs once) I see better/smoother working of the pages when loading in Page_Loadcomplete event. How are your experiences? I use Page_Prerender to set properties of a GridView other than DataSource and DataBind.
In Word you can only store 2 bytes. That is why I use Writer.
Assuming you're using ASP.NET 4.5 or later, don't use any of the above. Instead, set the
SelectMethod
on the control to the name of a method in your code-behind which returns the data. The control will then take care of calling the method whenever necessary. ScottGu's Blog - Web Forms Model Binding Part 1: Selecting Data (ASP.NET vNext Series)[^] ScottGu's Blog - Web Forms Model Binding Part 2: Filtering Data (ASP.NET vNext Series)[^] You can also useInsertMethod
,UpdateMethod
, andDeleteMethod
to perform basic CRUD operations on the data. ScottGu's Blog - Web Forms Model Binding Part 3: Updating and Validation (ASP.NET 4.5 Series)[^] And from ASP.NET 4.6 onwards, you can make theSelectMethod
a Task-returningasync
method as well. Cool ASP.NET Web Forms Features in 2015 – Async Model Binding - .NET Blog[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
Assuming you're using ASP.NET 4.5 or later, don't use any of the above. Instead, set the
SelectMethod
on the control to the name of a method in your code-behind which returns the data. The control will then take care of calling the method whenever necessary. ScottGu's Blog - Web Forms Model Binding Part 1: Selecting Data (ASP.NET vNext Series)[^] ScottGu's Blog - Web Forms Model Binding Part 2: Filtering Data (ASP.NET vNext Series)[^] You can also useInsertMethod
,UpdateMethod
, andDeleteMethod
to perform basic CRUD operations on the data. ScottGu's Blog - Web Forms Model Binding Part 3: Updating and Validation (ASP.NET 4.5 Series)[^] And from ASP.NET 4.6 onwards, you can make theSelectMethod
a Task-returningasync
method as well. Cool ASP.NET Web Forms Features in 2015 – Async Model Binding - .NET Blog[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
This is a horrible suggestion. Only tested SelectMethod. AJAX starts yelling about Registerscripts issues GridView can't set styling anymore via my Library (Node isues ??) And Async leads to exception it needs a return Task (which it is). Back to my way
In Word you can only store 2 bytes. That is why I use Writer.
-
This is a horrible suggestion. Only tested SelectMethod. AJAX starts yelling about Registerscripts issues GridView can't set styling anymore via my Library (Node isues ??) And Async leads to exception it needs a return Task (which it is). Back to my way
In Word you can only store 2 bytes. That is why I use Writer.
So... yeah. Don't show the code you tried, don't ask questions, don't describe any problems with proper detail, ... Just bash the suggestion with summary judgement because it wasn't as simple to implement as you expected. Sure.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave Kreskowiak -
So... yeah. Don't show the code you tried, don't ask questions, don't describe any problems with proper detail, ... Just bash the suggestion with summary judgement because it wasn't as simple to implement as you expected. Sure.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave KreskowiakBeen working all weekend on it. Using the SelectMethod and Creating the method in codebehind is no problem. But when everything stays yelling except loading data I am done with it. Read enough on it. Have over 11,000 users of this site of mine and I am not gonna take risks. Besides it is really strange that the SelectMethod in a page leads to a break in an UpdateProgress control in the masterpage. If I put that in comments, it is claiming for reducible nodes.
In Word you can only store 2 bytes. That is why I use Writer.
-
So... yeah. Don't show the code you tried, don't ask questions, don't describe any problems with proper detail, ... Just bash the suggestion with summary judgement because it wasn't as simple to implement as you expected. Sure.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave KreskowiakAnd now in CODE (used the ScottGu mentioned code in the link from first reply) Created a clean asp.net 4.7.2 webforms project. I have an ODATA service which is read via Unchase OData library Index.Asp has the gridview:
<%# Item.UserGroup.Count %>
My codebehind:
namespace TestGridView
{
public partial class Index : Page
{private Default.Container container; // is for working with the OData Service protected void Page\_Init(object sender, EventArgs e) { Uri uri = new Uri("http://localhost/api/global"); container = new Default.Container(uri) { Credentials = CredentialCache.DefaultNetworkCredentials, Timeout=3600 }; } protected void Page\_LoadComplete(object sender, EventArgs e) { GrdTest.BackColor = System.Drawing.Color.LightGreen; GrdTest.AlternatingRowStyle.BackColor = System.Drawing.Color.LightBlue; GrdTest.RowStyle.BackColor = System.Drawing.Color.LightGray; } // The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable GrdTest\_GetData(int? maximumRows, int? startRowIndex) { if (maximumRows == null || startRowIndex == null) return container.Users; return container.Users.Skip(startRowIndex ?? 0).Take(maximumRows ?? 0); } }
}
This will lead to 1 gridview without paging and shows data. Then I change my GridView to:
-
And now in CODE (used the ScottGu mentioned code in the link from first reply) Created a clean asp.net 4.7.2 webforms project. I have an ODATA service which is read via Unchase OData library Index.Asp has the gridview:
<%# Item.UserGroup.Count %>
My codebehind:
namespace TestGridView
{
public partial class Index : Page
{private Default.Container container; // is for working with the OData Service protected void Page\_Init(object sender, EventArgs e) { Uri uri = new Uri("http://localhost/api/global"); container = new Default.Container(uri) { Credentials = CredentialCache.DefaultNetworkCredentials, Timeout=3600 }; } protected void Page\_LoadComplete(object sender, EventArgs e) { GrdTest.BackColor = System.Drawing.Color.LightGreen; GrdTest.AlternatingRowStyle.BackColor = System.Drawing.Color.LightBlue; GrdTest.RowStyle.BackColor = System.Drawing.Color.LightGray; } // The return type can be changed to IEnumerable, however to support // paging and sorting, the following parameters must be added: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable GrdTest\_GetData(int? maximumRows, int? startRowIndex) { if (maximumRows == null || startRowIndex == null) return container.Users; return container.Users.Skip(startRowIndex ?? 0).Take(maximumRows ?? 0); } }
}
This will lead to 1 gridview without paging and shows data. Then I change my GridView to:
Sorting needs to be applied before the paging. In your first example, you've returned a page of unsorted records, and are then trying to sort them. That's the most likely cause of the error. In your second example, you've defined the sorting parameter, so your code is responsible for sorting the data. The model binding won't try to sort the returned data again.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
Sorting needs to be applied before the paging. In your first example, you've returned a page of unsorted records, and are then trying to sort them. That's the most likely cause of the error. In your second example, you've defined the sorting parameter, so your code is responsible for sorting the data. The model binding won't try to sort the returned data again.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Even if I set in the GridView:
AllowSorting="true" AllowPaging="true" PageSize="10"
Still I have
[ArgumentException: must be reducible node]
System.Linq.Expressions.Expression.VisitChildren(ExpressionVisitor visitor) +97
System.Linq.Expressions.ExpressionVisitor.VisitExtension(Expression node) +11
System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor) +12
System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) +20
System.Web.Util.OrderingMethodFinder.OrderMethodExists(Expression expression) +38
System.Web.UI.WebControls.QueryableHelpers.IsOrderingMethodFound(IQueryable`1 queryable) +16[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +168
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +105
System.Web.UI.WebControls.ModelDataSourceView.ProcessSelectMethodResult(DataSourceSelectArguments arguments, DataSourceSelectResultProcessingOptions selectResultProcessingOptions, ModelDataMethodResult result) +393
System.Web.UI.WebControls.ModelDataSourceView.GetSelectMethodResult(DataSourceSelectArguments arguments) +86
System.Web.UI.WebControls.ModelDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +14
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +17
System.Web.UI.WebControls.ModelDataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +81
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +169
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +71
System.Web.UI.WebControls.GridView.DataBind() +5
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +93
System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +72
System.Web.UI.Control.EnsureChildControls() +116
System.Web.UI.Control.PreRenderRecursiveInternal() +49
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4719 -
Even if I set in the GridView:
AllowSorting="true" AllowPaging="true" PageSize="10"
Still I have
[ArgumentException: must be reducible node]
System.Linq.Expressions.Expression.VisitChildren(ExpressionVisitor visitor) +97
System.Linq.Expressions.ExpressionVisitor.VisitExtension(Expression node) +11
System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor) +12
System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) +20
System.Web.Util.OrderingMethodFinder.OrderMethodExists(Expression expression) +38
System.Web.UI.WebControls.QueryableHelpers.IsOrderingMethodFound(IQueryable`1 queryable) +16[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +168
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +105
System.Web.UI.WebControls.ModelDataSourceView.ProcessSelectMethodResult(DataSourceSelectArguments arguments, DataSourceSelectResultProcessingOptions selectResultProcessingOptions, ModelDataMethodResult result) +393
System.Web.UI.WebControls.ModelDataSourceView.GetSelectMethodResult(DataSourceSelectArguments arguments) +86
System.Web.UI.WebControls.ModelDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +14
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +17
System.Web.UI.WebControls.ModelDataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +81
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +169
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +71
System.Web.UI.WebControls.GridView.DataBind() +5
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +93
System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +72
System.Web.UI.Control.EnsureChildControls() +116
System.Web.UI.Control.PreRenderRecursiveInternal() +49
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4719It's almost certainly the OData service which is causing the problem. Try turning off sorting and adding
.OrderBy(x => x.Name)
to see if you get the same error.public IQueryable<User> GrdTest_GetData(int? maximumRows, int? startRowIndex)
{
IQueryable<User> result = container.Users.OrderBy(x => x.Name);
if (maximumRows != null && startRowIndex != null)
{
result = result.Skip(startRowIndex ?? 0).Take(maximumRows ?? 0);
}return result;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
It's almost certainly the OData service which is causing the problem. Try turning off sorting and adding
.OrderBy(x => x.Name)
to see if you get the same error.public IQueryable<User> GrdTest_GetData(int? maximumRows, int? startRowIndex)
{
IQueryable<User> result = container.Users.OrderBy(x => x.Name);
if (maximumRows != null && startRowIndex != null)
{
result = result.Skip(startRowIndex ?? 0).Take(maximumRows ?? 0);
}return result;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Unfortunately the error stays.... Maybe some help: [Expression.VisitChildren(ExpressionVisitor) Method (System.Linq.Expressions) | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.visitchildren?view=net-6.0)
In Word you can only store 2 bytes. That is why I use Writer.
-
Unfortunately the error stays.... Maybe some help: [Expression.VisitChildren(ExpressionVisitor) Method (System.Linq.Expressions) | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.visitchildren?view=net-6.0)
In Word you can only store 2 bytes. That is why I use Writer.
That just confirms that your OData service client doesn't support LINQ ordering. I'm not familiar with the library you're using. Does it provide some other method to sort the results?
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
That just confirms that your OData service client doesn't support LINQ ordering. I'm not familiar with the library you're using. Does it provide some other method to sort the results?
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
The Unchase OData client (UOC) creates the connection between the client (WebForm) and the OData service (over IIS). In IIS OData controllers send the data over the HTTPGet when requested. The UOC uses linq to translate the linq query to OData HTTP request. The Reference.cs created by the UOC shows even the connections between tables in the DB over ODATA. What I now suspect is that the controller in the IIS does:
return db.Users.Where(x => !x.IsDeleted)
It is not using Include("UserGroups") to fill these nodes with data. The linq query translates to requerst Uri: http://localhost/api/global/Users?$orderby=Id
In Word you can only store 2 bytes. That is why I use Writer.