How to get GridView to Persist

Coreysan 1,606 Reputation points
2021-10-19T00:38:02.153+00:00

I have a small classic asp.net app, and I have a GridView that is hidden:
<asp:GridView ID="grid1" runat="server" Visible="false" AutoGenerateColumns="true"></asp:GridView>

On initialization in the codebehind, I populate the GridView and I'm happy!

But, when there's a PostBack, its immediately empty.

I know in other apps I have it persists on PostBack, but not in this one. I'm sure I'm forgetting something.
I don't have a method which clears the data - that would be silly. (But I'll double check).

Any thoughts?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,222 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Lan Huang-MSFT 24,461 Reputation points Microsoft Vendor
    2021-10-19T06:13:33.35+00:00

    Hi @Coreysan ,
    1.First check whether dts has values,
    2.Are these two lines of code written in !IsPostBack?

    grid1.DataSource = dts;  
    grid1.DataBind();  
    

    3.Is there an updatepanel in the code.
    Maybe you can provide more detailed code to help you solve the problem.
    Below is the demo I wrote, maybe you can refer to it:

    protected void Page_Load(object sender, EventArgs e)  
     {  
          SqlConnection conn = new SqlConnection(@"Data Source=****");  
          if (!IsPostBack)  
          {  
             DataTable dts = new DataTable();  
             string str = "select * from data";  
             SqlDataAdapter adp = new SqlDataAdapter(str, conn);  
             adp.Fill(dts);  
             grid1.DataSource = dts;  
             grid1.DataBind();  
           }  
      }  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Coreysan 1,606 Reputation points
    2021-10-19T17:55:18.93+00:00

    @Lan Huang-MSFT - I read through a lot of examples on StackOverflow and the older forums.asp.net, and finally discovered my solution:

    Instead of passing GridView as a session variable, I passed a DataTable. Once I did that, everything worked.

    I don't understand it, but there you go. Something about the GridView!!!

    Thanks for your involvement!

    0 comments No comments