In this article, we will learn how to save a DataTable in ViewState and bind it to a GridView. In case, a new record is being added, the DataTable is fetched from the ViewState, updated, and used again to bind the GridView.

Bind GridView using Datatable and ViewState using ASP.NET

DataTable represents a single in-memory database table with rows and columns. It allows us to fetch on TableRow at a time and does not contain any DataRelation object. You can load an entire table into the DataTable and can manipulate the values in the table.

ViewState is an important state management technique used at the client end. It contains the user’s data stored within the page itself.

GridView controls is a powerful feature allows you to select, sort, or edit these values.

Let’s start with creating a new GridVeiw. Add two columns to the Grid as shown below:

    <asp:GridView ID="BooksGridView" runat="server" CssClass="gv" AutoGenerateColumns="false"
        EmptyDataText="No records Found.">
        <Columns>
            <asp:BoundField
                DataField="CustomerName"
                HeaderText="Customer Name"
                ItemStyle-Width="120" />
            <asp:BoundField
                DataField="CustomerEmail"
                HeaderText="Customer Email"
                ItemStyle-Width="120" />
        </Columns>

    </asp:GridView>

Initially, when a DataTable is created, then few records are added to it before it is saved in the ViewState.

The BindGridView() method is called to populate the GridView with the data from DataTable, which is saved in the ViewState variable.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[2] { new DataColumn("CustomerName"),
                new DataColumn("CustomerEmail") });
            // add a customer
            DataRow dr;
            dr = dt.NewRow();
            dr["CustomerName"] = "Scott";
            dr["CustomerEmail"] = "scott@companyEmail.com";
            dt.Rows.Add(dr);

            // add another customer
            dr = dt.NewRow();
            dr["CustomerName"] = "Eddy";
            dr["CustomerEmail"] = "eddy@companyEmail.com";
            dt.Rows.Add(dr);
            ViewState["Customers"] = dt;

            BindGridView();
        }
    }

Related Articles

Last modified: November 17, 2019

Comments

Write a Reply or Comment

Your email address will not be published.