GridView Control and its application in ASP.net

$INeed$

Well-Known Member
GridView Control and its application in ASP.net

Here in this section we will learn about the gridview control and its application in asp.net. One of the reason behind the popularity of Dot net application is due to the use of GridView Control. A GridView Control helps to connect to a datasource and display information/data in a tabular fromat thus providing flexibility in displaying and working with data/information from the database.With the help of a gridview control we can also “Delete”, “Edit”, “Update” data from database.

Here I have used “Online shopping application” as the example.

Example:

To View All the products from the database using gridview control and also edit,update,delete products from database during runtime.

To select the gridview tool

Step 1: Go to View

Step 2: Click Toolbox

Step 3: Under “Data” double click “GridView”.

To change the look/style of a gridview,to edit columns, all this i have explained in a diagramtic view.

Picture
In the above picture we can see the arrow.If we click here a GridView Tasks sidebox open.Here we can change formats of the gridview,add columns,edit columns,edit templates.

To change the format of the gridview

Step 1: Click the “Auto Format” as seen in the above image.

Step 2: After Clicking Choose the Scheme accordingly.

Step 3: Click “Apply” then “Ok”

To Add and edit Columns in a gridview

Step 1: As shown in the above picture click “Add New Columns” from the gridview tasks side box.We can also click “Edit Columns” and can add from their. After clicking a box opens as shown in the below picture.

Step 2: Select the “Template Field” click “Add” button.

*Note- Here we are choosing template field as because we will be fetching all the data/images from the database and we also edit,delete,update during runtime which can be done using template field

Step 3: Now Write the header text for example ”ProductImage” and click ok.Smilary Add all the columns.

Edit Templates

Step1: In the “GridView Tasks” side box click “Edit Template”. A box open as shown in the below screenshot.


Step 2 - Here we can see that a “Template Editing Mode” side Boxes opens where all the columns are represented listwise.Select the Column which you want to edit.

Step 3 - After selecting the column drag a tool in which you want to display the data.Suppose you want to display the product name in column[1] then drag a “Label” tool to the item template. Here in the above picture you can see column[0] is the “ProductImage” so to display a image from the database we need to choose a “Image” tool from the toolbox and drag it to the “ItemTemplate” section as shown in the above.

Step 4- Now to fetch the image from the database we have to go to Image Tasks side box and then “Edit Bindings” as shown in the below screenshot

Step 5 -After clicking editbndings-aboxs opens as shown

Step 6 - We can see “Code Expression” where the image url is written. “images” is the name of the folder where all the product images have been uploaded.
Now as we want to fetch all the data from the product table so we will use the same name and pattern we used in the product table. For Example:

ProductName will be written as Eval(“ProductName”)

productdesc will be written as Eval(“productdesc”)

Productid will be written as Eval(“Productid”)

ProductImage will be wriiten as “images” + Eval(“ProductImage”). Here we need the path(i.e the folder name) where the images are stored.

Now coming to the EditItemTemplate:

The EditItemTemplate is mainly used when a edit function is called. Here in the above examples we see that the in the EditItemTemplate section a textbox is dragged. This is because when the edit button is clicked the textbox appears in order to edit the product name. Similarly all the columns can have textbox in the EditItemTemplate. The ProductImage Column needs to have fileupload tool as because to change the image we cannot use textboxs.

Now while adding columns we have added two more named as “Edit” and “Delete”.


1. In the ItemTemplate section a image button is dragged.Now during runtime this button is used to edit the row.

Important -> To Used the Button to Edit Follow the below step:

a) Go to Properties or click F4.

b) From the properties go to “Command Name” and type- Edit.

Now In the EditItemTemplate more two image buttons are used

1. A update button -> to used the button to update follow the below step:

a) Go to Properties or click F4.

b) From the properties go to “Command Name” and type - Update.

2. A cancel button -> to used the button to cancel follow the above step and type the “Command Name”- Cancel.

Afer completing all the steps above go to GridView Tasks side box and click “End Template Editing”.

Now the Gridview will look like we want to.

*Note- If it does’nt look exactly like this then select the GridView,Type F4, from the properties go to AutoGenerateColumns and change it to “False”.

Paging

In order to enable Paging in a gridview.

Step1- Go to Properties

Step 2 - Make “AllowPaging” property “true”

Step 3 - From the properties go to ‘PagerSetting” and make changes in the setting like “PageButtonCount”, “Mode” etc.

Step 4 - From properties go to “PagerStyle” and change the color look of the pages.

The source code to enable paging in a grid view asp.net is below->

Код:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        populateTemplateGrid();

        GridView1.PageIndex = e.NewPageIndex;

        GridView1.DataBind();

    }

Complete Source Code Of the Above Example i.e To View All the products from the database using gridview control and also edit,update,delete products from database during runtime

Source Codes

Код:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class manageproduct : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (this.IsPostBack == false)

        {

            populateproduct();

        }

    }

    private void populateproduct()

    {

        String myconstring = System.Configuration.ConfigurationManager.ConnectionStrings["OurDatabaseConnectionString1"].ConnectionString;

        SqlConnection con = new SqlConnection(myconstring);

        con.Open();

        String query = "select * from product";

        SqlCommand com = new SqlCommand(query, con);

       

        SqlDataAdapter da = new SqlDataAdapter(com);

     

        DataSet ds = new DataSet();

       

        da.Fill(ds);

        con.Close();

        GridView1.DataSource = ds.Tables[0];

        GridView1.DataBind();

    }

   

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

     

        int rowindx = e.NewEditIndex;

       

   

        GridView1.EditIndex = rowindx;

    

        populateTemplateGrid();

    }

    private void populateTemplateGrid()

    {

        String myconstring = System.Configuration.ConfigurationManager.ConnectionStrings["OurDatabaseConnectionString1"].ConnectionString;

        SqlConnection con = new SqlConnection(myconstring);

        con.Open();

        String query = "select * from product";

        SqlCommand com = new SqlCommand(query, con);

      

        SqlDataAdapter da = new SqlDataAdapter(com);

       

        DataSet ds = new DataSet();

       

        da.Fill(ds);

        con.Close();

        GridView1.DataSource = ds.Tables[0];

        GridView1.DataBind();

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

       

        int rowindx = e.RowIndex;

       

        Label Label1 = (Label)GridView1.Rows[rowindx].FindControl("Label1");

        Label Label2 = (Label)GridView1.Rows[rowindx].FindControl("Label2");

        TextBox TextBox1 = (TextBox)GridView1.Rows[rowindx].FindControl("TextBox1");

        TextBox TextBox2 = (TextBox)GridView1.Rows[rowindx].FindControl("TextBox2");

        TextBox TextBox3 = (TextBox)GridView1.Rows[rowindx].FindControl("TextBox3");

        Image Image1 = (Image)GridView1.Rows[rowindx].FindControl("Image1");

        FileUpload FileUpload1 = (FileUpload)GridView1.Rows[rowindx].FindControl("FileUpload1");

        String query = "update product ";

        query += " set ProductName='" + TextBox1.Text + "',";

        query += " OurPrice='" + TextBox2.Text + "',";

        query += " ProductDescription='" + TextBox3.Text + "',";

        String filename = "";

        if (FileUpload1.HasFile)

        {

            filename = Path.GetFileName(FileUpload1.PostedFile.FileName);

            FileUpload1.PostedFile.SaveAs(Server.MapPath( "images/"+ filename));

            Image1.ImageUrl = filename;

         }

           

       

       query += " ProductImage='" + Image1.ImageUrl + "'";

        query += " where ProductID='" + Label2.Text + "'";

       

        String myconstring = System.Configuration.ConfigurationManager.ConnectionStrings["OurDatabaseConnectionString1"].ConnectionString;

        SqlConnection con = new SqlConnection(myconstring);

        con.Open();

        SqlCommand com = new SqlCommand(query, con);

        int res = com.ExecuteNonQuery();

        if (res == 1)

        {

           

            GridView1.EditIndex = -1;

            populateTemplateGrid();

        }

        con.Close();

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

       

        populateTemplateGrid();

    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

       

        int rowindx = e.RowIndex;

        Label Label2 = (Label)GridView1.Rows[rowindx].FindControl("Label2");

        String query = "delete from product ";

        query += " where ProductID='" + Label2.Text + "'";

        String myconstring = System.Configuration.ConfigurationManager.ConnectionStrings["OurDatabaseConnectionString1"].ConnectionString;

        SqlConnection con = new SqlConnection(myconstring);

        con.Open();

        SqlCommand com = new SqlCommand(query, con);

        int result = com.ExecuteNonQuery();

        if (result == 1)

        {

            GridView1.EditIndex = -1;

            populateTemplateGrid();

        }

        con.Close();

   

    }

   

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        populateTemplateGrid();

        GridView1.PageIndex = e.NewPageIndex;

        GridView1.DataBind();

    }
 

Горе