DataGridView Operations in ASP.Net

The main focus of this article is to show how DataGridView works. Some simple operations are also done here, like add, delete, clear and so on.

First Approach: Using Datatable

Advantages

  • A DataTable is an easy to use variable that allows the user to pull data into it with a consistent format and embed it with other properties that allow us to do sorting, searching and so on.

  • It is easy to easily customize.

  • It allows implementing business logic using properties.

Working Details

Open your Visual Studio 2012 and open a new project.

  1. Select Windows on the left side menu bar.

  2. Select Windows Forms application.

  3. Provide the name of the project.

  4. Select the directory/location to store the project.

    windows form application

          Form Design

Form Design

  1. Select your form and add a DataGridView from the toolbox.

  2. Name it DataGridView2.

        Coding Structure

  1. Declare a datatable orderstable globally.

  2. Now for the definition of the CreateOrdersTable() and Bindata() methods.

  3. In the CreateOrdersTable() method declare a data column and a data row. Then add a column and row to the orders table. In the same way you can add multiple columns and rows to the datatable.

  4. In the binddata method just add the data source to the datatable name.

    binddata method

  5. Run the demo project and you will see the output like this.

    data source to the datatable

    Second Approach: Using List

    Advantages

  • Dynamically auto-size the array. You just need to specify the type of data initially.

  • Comparatively faster than a data table.

   List Declaration

List Declaration

     Ui Action

Ui Action

       Save Method Action

Save Method Action

       Method Definition

       The following are Actions.

  1. Check whether or not a row is selected.

  2. Declaring a list locally and add new items to the list.

  3. Calling an event for showing new items in the grid view.

   Delete Method Action

       Method Definition.

       The following are the Actions.

  1. Check whether a row is selected.

  2. The selected row is kept in a variable and removed from the row from the list.

  3. The following shows how to call a method for showing the grid view data after deleting the row.

    Delete Method Action

Next Recommended Readings