C# Solution for an empty DataTable after postback

How often do you use Postbacks on asp.net pages? How often do you use it in SharePoint? Well, if you are using postbacks you might know that if you bind your data to a source, e.g. a datatable, the datatable is null after postback. Ok, you can bind your data all the time again meaning you also making request every time against the datasource (database or sharepoint list, etc.).

Well, if you like to store the data which you will bind to a control in a place where it stays? I used the viewstate. I got the hint from this discussion. And used it right this way:

[sourcecode language=”csharp”]

DataTable ds = new DataTable();

//… fill here your Datatable

ViewState.Add(“TicketDaten”, ds);

 

//After Postback reload it

ds = ViewState[“TicketDaten”] as DataTable;

[/sourcecode]

Hope it helps you!

..:: I Like SharePoint ::..

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Karsten Schneider 312 Articles
Consultant for Microsoft 365 Applications with a strong focus in Teams, SharePoint Online, OneDrive for Business as well as PowerPlatform with PowerApps, Flow and PowerBI. I provide Workshops for Governance & Security in Office 365 and Development of Solutions in the area of Collaboration and Teamwork based on Microsoft 365 and Azure Cloud Solutions. In his free time he tries to collect tipps and worthy experience in this blog.

3 Comments

  1. Have you also thought about the Session object?

    The ViewState gets serialized and is transmitted with every single page action.

  2. As Timm already mentioned, the ViewState might not be the best solution. Server-side Caching could be a better approach.
    Both ways the datasource is queried only once. The data is transferred too often through the potentially small bandwith Internet connection 🙁

Leave a Reply

Your email address will not be published.


*