Table of contents
1.
Introduction
2.
Syntax
3.
Fields
4.
Properties
5.
Methods
6.
Events
7.
How is an ASP.NET Datagrid made?
8.
Example Using DataGrid in ASP.NET
8.1.
DataGridTask.aspx
8.1.1.
Connect to the Database
8.2.
Table records in SQL Server
9.
FAQs
10.
Key Takeaway
Last Updated: Mar 27, 2024

ASP.NET DataGrid

Author Aditya Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We can use the Datagrid control from the ASP.NET framework to display any scrollable table with data using the Datagrid control from the ASP.NET framework. It will display data in a tabular format derived from JSON (JavaScript Object Notation) or online services. A more appealing and upgraded UI can be created utilising the Datagrid widget. It has additional capabilities than the ASP.NET web form's essential gridview control. It will show one of two things: either a single table or the hierarchical relationship between a group of tables.

The ASP.NET Datagrid control includes many features, including editing, filtering, grouping, paging, data binding with adaptors, and much more.

Syntax

<asp:DataGrid ID="Grid" runat="server" >
<Columns>
<asp:BoundColumn HeaderText="EmpId" DataField="EmpId"> </asp:BoundColumn>
</Columns>
</asp:DataGrid>

 

Header text is used to convey the header's text and its value.

Because this is a server-side application, the runat is set to "server."

Their column kinds determine the behaviour of the columns in control. The different column types that can be used are listed in the table below.

Column Type Description
BoundColumn Displays a column in a data source connected to a field. Each item in the field is displayed as text. The DataGrid control's default column type is this.
ButtonColumn For each item in the column, a command button is displayed. You can use this to make a column of custom button controls, such as Add and Remove buttons.
EditCommandColumn It Displays a column with editing controls for each column's item.
HyperLinkColumn Each item in the column's content is displayed as a hyperlink. The column's contents might be tied to a data source field or static text.
TemplateColumn Each item in the column is displayed according to a template. This allows you to customise the column by adding custom controls.

 

Fields

In ASP.NET, DataGrid has all the mentioned fields, which are given below:

Field name Description
CancelCommandName Cancel is the name of the command. This is a read-only field.
DeleteCommandName It shows the delete command name. This is a read-only field.
EditCommandName This variable represents the Edit command's name. This is a read-only field.
NextPageCommandArgument This object represents the Next command argument. This is a read-only field.
PageCommandName It shows the page command name. This is a read-only field.
PrevPageCommandArgument This object represents the Prev command argument. This is a read-only field.
SelectCommandName This variable represents the Select command's name. This is a read-only field.
SortCommandName It shows the sort command name. This is a read-only field.
UpdateCommandName It shows the update as a command name. This is a read-only field.

 

Properties

In ASP.NET, DataGrid have many properties, and a few of them are mentioned below:

Property Name Description
AccessKey Gets or sets the access key to navigate the Web server control rapidly.
Adapter This will get the control's browser-specific adaptor.
AllowCustomPaging This property gets or sets a value that specifies whether or not custom paging is enabled.
AllowPaging This property gets or sets a value indicating whether paging is enabled.
AllowSorting This method returns or sets a value that specifies whether or not sorting is enabled.
AlternatingItemStyle This will get the style properties for the DataGrid control's alternating items.
AppRelativeTemplateSourceDirrectory The application-relative virtual directory of the Page or UserControl object containing this control is retrieved or set.
Attributes Get a collection of arbitrary characteristics (for rendering only) that don't match any control's properties.
AutoGenerateColumns Gets or sets a value that determines whether BoundColumn objects for each field in the data source are automatically constructed and shown in the DataGrid control.
BackColor This will get or set the Web server control's background colour.
BackImageUrl Gets or sets the URL of an image to display in the DataGrid control's background.
BindingContainer Gets the control that has the data binding for this control.

 

Methods

In ASP.NET DataGrid have different methods which are mentioned below:

Method  Description
AddAttributesToRender(HtmlTextWriter() Adds HTML propehass and styles to . AlTextWriterTag that must be rendered. Control developers are the most common users of this technology.
AddedControl(Control, Int32) This method is called when a child control is added to the Control object's Controls collection.
AddParsedSubObject(Object) Notifies the server control that an element, either XML or HTML, has been processed and adds it to the ControlCollection collection.
ApplyStyle(Style) This will overwrite any existing style elements in the Web control with any non blank components of the supplied style. Control developers are the most common users of this technology.
ApplyStyleSheetSkin(Page) The page style sheet's style settings are applied to the control.
BeginRenderTracing(TextWriter, Object) Starts tracing rendering data during design time.
BuildProfileTree(String, Boolean) When tracing is enabled for the page, this property collects information about the server control and sends it to the Trace property to be shown.
ClearCachedClientID() Sets the ClientID value in the cache to null.
ClearChildControlState() Deletes the server control's child controls' control-state information.
ClearChildState() All of the server control's child controls' view-state and control-state information is deleted.
ClearChildViewState() Deletes all of the server control's child controls' view-state information.
ClearEffectiveClientIDMode() The current control instance's ClientIDMode property and any child controls are set to Inherit.
CopyBaseAttributes(WebContol) Copies the attributes from the specified Web server control that are not wrapped by the Style object to the Web server control from which this method is called. Control developers are the most common users of this technology.

 

Events

In ASP.NET, DataGrid has different events mentioned below:

Event Name Description
CancelCommand When the Cancel button for an item in the DataGrid control is clicked, this event occurs.
DataBinding When the server control binds to a data source, this event occurs.
DeleteCommand When the Delete button for an item in the DataGrid control is clicked, this event occurs.
ItemDataBound This event occurs after data is linked to the DataGrid control.
EditCommand When the Edit button for an item in the DataGrid control is clicked, this event occurs.
Init This occurs during the initialisation of the server control, which is the first stage in its lifespan.
ItemCommand When a button in the DataGrid control is clicked, this event occurs.

 

Must read topic: .Net

How is an ASP.NET Datagrid made?

Let's look at the DataGrid in ASP.NET and learn about it using snippets. Let's look at how to make an ASP.NET DataGrid.

Steps:

  1. Establish a visual studio. Create a new blank form now. For more information, see the snippet below.


2. Go to the toolbox and look for DataGrid. Select it and drag it to the new empty form.

 

3. This Data grid will appear like the image below after being dragged. It will generate a table with rows and columns for us.

Example Using DataGrid in ASP.NET

With the use of an example, we can gain a deeper understanding. So let us take an example displaying a table containing a First name, Last name, Contact, Email and Address. Here is the example:

DataGridTask.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="BindGridview.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvPhoneBook" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText ="First Name" />
                <asp:BoundField DataField="LastName" HeaderText ="Last Name" />
                <asp:BoundField DataField="Contact" HeaderText ="Contact" />
                <asp:BoundField DataField="Email" HeaderText ="Email" />
                <asp:BoundField DataField="Address" HeaderText ="Address" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkSelect" Text="Select" runat="server" CommandArgument='<%# Eval("PhoneBookID") %>' OnClick="lnkSelect_Click"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Connect to the Database

We have code for database connectivity, and binding fetched records to the DataGrid in the CodeBehind file.

DataGridTask.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;

namespace BindGridview
{
    public partial class Index : System.Web.UI.Page
    {
        string connectionString = @"Data Source=(local)\sqle2012; Initial Catalog = PhoneBookDB; Integrated Security=True;";
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM PhoneBook", sqlCon);
                DataTable dtbl = new DataTable();
                sqlDa.Fill(dtbl);
                gvPhoneBook.DataSource = dtbl;
                gvPhoneBook.DataBind();
            }
        }

        protected void lnkSelect_Click(object sender, EventArgs e)
        {
            int phoneBookID = Convert.ToInt32((sender as LinkButton).CommandArgument);
        }
    }
}

Table records in SQL Server

We wish to use the DataGrid to display records from a PhoneBook table. The following records are found in this table.

Output:

This programme retrieves records from the SQL server and shows them in the web browser after it has been run.

FAQs

  1. What is DataGrid in ASP.NET?
    The DataGrid control in the.NET framework displays data on a web page. It first appeared in.NET 1.0 and has since been deprecated. DataGrid is a scrollable grid that displays data. To populate data in the grid will require a data source.
     
  2. What is the use of the CancelCommand event?
    When the Cancel button for an item in the DataGrid control is clicked, this event occurs.
     
  3. What is the use of BoundColumn?
    Displays a column in a data source that is connected to a field. Each item in the field is displayed as text. The DataGrid control's default column type is this.
     
  4. Name any two methods which are used in DataGrid in ASP.NET.
    ApplyStyle(Style): Overwrites any existing style elements in the Web control with any nonblank components of the supplied style. Control developers are the most common users of this technology.
    ClearChildState(): All of the server control's child controls' view-state and control-state information is deleted.
     
  5. Define any one property of DataGrid in ASP.NET.
    AllowPaging: This property gets or sets a value indicating whether paging is enabled.

Key Takeaway

We've gone over the Datagrid control in this article. I hope you have a better understanding of how the Datagrid control is built and utilised today. Data grid web server control is a multi-column data-bound grip. We realised that it has a wide range of functions and is very effective for displaying a scrollable table.

Apart from this, you can also expand your knowledge by referring to these articles on Features Of ASP Net and ASP Full Form.

You can also explore many other open-source, server-side web-application frameworks other than ASP.net with the article Top 10 web development frameworks.

Happy Learning!

Live masterclass