How to store datatable in viewstate:
In the page load event and button click event write below code
In the page load event i am getting datatable from emp table and storing it in viewstate. in button click event i am getting viewstate emptable and binding that table to gridview. In this way you can store large amount of data in viewstate but it will increase the page size.
Description:
In this example i will get data table from database and store it in viewstate in page load event and then in button click event i will get data table from viewstate and populates it in gridview. This is the example how to store large volumes of data in viewstate.
Take form which contains a label,a button and gridview like below
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
- GridLines="None"
- style="z-index: 1; left: 279px; top: 121px; position: absolute; height: 133px; width: 187px">
- <alternatingrowstyle BackColor="White" />
- <editrowstyle BackColor="#7C6F57" />
- <footerstyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
- <headerstyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
- <pagerstyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
- <rowstyle BackColor="#E3EAEB" />
- <selectedrowstyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
- <sortedascendingcellstyle BackColor="#F8FAFA" />
- <sortedascendingheaderstyle BackColor="#246B61" />
- <sorteddescendingcellstyle BackColor="#D4DFE1" />
- <sorteddescendingheaderstyle BackColor="#15524A" />
- </asp:GridView>
- <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
- style="z-index: 1; left: 284px; top: 80px; position: absolute"
- Text="LoadData" />
- <asp:Label ID="Label1" runat="server" BackColor="#CCCCCC" ForeColor="#FF0066"
- style="z-index: 1; left: 325px; top: 54px; position: absolute; width: 354px"></asp:Label>
- </div>
- lt;/form>
In the page load event and button click event write below code
- protected void Page_Load(object sender, EventArgs e)
- {
- SqlConnection con = new SqlConnection("database=cs9db;user id=sa;password=9290812112;data source=(local);");
- SqlDataAdapter da = new SqlDataAdapter("Select * from emp where deptno="+30, con);
- DataTable dt = new DataTable();
- da.Fill(dt);
- ViewState["EmpTable"] = dt;// storing datatable in viewstate
- Label1.Text = "Data Table stored in viewstate";
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- GridView1.DataSource = (DataTable)ViewState["EmpTable"];// retrieving datatable from viewstate
- GridView1.DataBind();
- Label1.Text = "View state datatable is displayed in gridview";
- }
In the page load event i am getting datatable from emp table and storing it in viewstate. in button click event i am getting viewstate emptable and binding that table to gridview. In this way you can store large amount of data in viewstate but it will increase the page size.
No comments:
Post a Comment