Friday 12 April 2013

Gridview in Asp.net- Part 1

Written By:- Isha Malhotra(malhotra.isha3388@gmail.com)
If you find this article useful then leave your comment
Gridview - Part 1

Gridview is used to show the data on your Screen from database. In this article I will explain how to work with gridview. Following are some functionality which we can perform on gridview.

Show Data in Gridview

To show the data on gridview first add gridview on your form and select the data from database by using the following connectivity:-
Default.aspx.cs:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Create connection. kindly change the conn_string according to your system

            string conn_string = "Data Source=Isha-PC;Initial Catalog=TechAltum;Integrated Security=True";
            SqlConnection con = new SqlConnection(conn_string);

            //create command object
            SqlCommand cmd = new SqlCommand();

            //pass connection and query to your command object
            cmd.Connection = con;
            cmd.CommandText = "Select * from Prod_rep";

            //create adaptor to fill data from database
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            //create datatable which holds the data
            DataTable dt = new DataTable();
            da.Fill(dt);

            //bind your data to gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}



The output of this example as follows:-



Figure 1
In this way we can show data on gridview.

Add Controls in Gridview

If we need to add control controls in gridview then we use Template field in gridview.

For Example:-

Everybody is familier here with the gmail. You can see in gmail it shows our mail in tabular format as gridview shows and in the first coloumn there is checkbox here. And if we checked any checkbox then we can delete our selected mail. Same example I am taking here. I am adding checkbox the gridview using Template fielde.
Following are the steps to perform this task:-

Step 1:- click on the smart tag of Gridview and Select Edit Column



Figure 2

Step 2:-Select TemplateField and click on add button



Figure 3

Step 3:-Add header Text which you want to show in the table.



Figure 4

Similary you have to add all columns which you want to show in the gridview. While creating this template field you have to uncheck the autogenerate fileds so that it will add only that field which you add through  manually using template field.



Figure 5

After that click on ok button. You will see your gridview as follows:-



Figure 6

Step 4:- now we have to add some controls in the gridview. Now click on smart tag again select the Edit Template Field .



Figure 7
After clicking of Edit templates you will get the following screen



Figure 8

Step 5:- in this list you will see all your column which you added at the time of edit column. Now we have to add our control in the gridview. We have to add control in the ItemTemplate area, which shows in the following figure.



Figure 9

Similarly add another control to show the data in the gridview next column. For other column I am taking label control on which I want to show the other column data which is as follows:-

Select next column from the list and select its Item Template.



Figure 10
Now add label in the item template.



Figure 11

As we know that we need to show the data of that column in the gridview. To show data in the controls we need to bind the data. When we add any control in the gridview it shows edit DataBinding option.



Figure 12

In this area we need to bind the column which we want to show in this column.

Similarly add another column and after that click on End Template Editing.



Figure 13
Note:-coding of Default.aspx.cs will remain same.

Now execute your code. The output of this code as follows:-



Figure 14
Now lets fetch the selected data which is checked by user and show the sum of all no of prod.
For Example:-

protected void Button1_Click(object sender, EventArgs e)
    {
        int sum = 0;
        //Traverse the gridview
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            //find the control in gridview and check whether it is selected or not
            if (((CheckBox)(GridView1.Rows[i].FindControl("CheckBox1"))).Checked)
            {
                //fetch the value of no of prod which we bind on label 3
                int x = Convert.ToInt32(((Label)(GridView1.Rows[i].FindControl("Label3"))).Text);
                sum = sum + x;

           
            }
       
        }
        Response.Write(sum);
    }

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
        Gridview:-<br />
   
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:TemplateField HeaderText="Select">
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Prod Year">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# bind("Prod_year") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Dept">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# bind("Dept") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="No of Prod">
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# bind("No_of_Prod") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Sum" onclick="Button1_Click" />
    <br />
    </form>
</body>
</html>

The output of this code as follows:-



Figure 15

Hope you enjoyed the article. In my next article I will discuss more about Gridview.

2 comments: