In our previous tutorial, you have learned how to create a table in ASP.NET and how to populate ASP.NET table dynamically. There are multiple properties of tables in ASP.NET. For example, you can perform add, update and delete operations on rows and columns of ASP.NET tables. In this tutorial, you will learn how to use GridView in ASP.NET.
GridView is the successor of DataGrid. GridView manages the data from the database properly in tabular form. GridView can also create its DataSet and can directly connect to the database i.e. SQL server.
Properties of GridView in ASP.NET
Similar to the table and DataGrid, you can also set multiple properties of DataGrid like BackColor, Font, and ForeColor along with the header, row, and footer styles.
Creating GridView in ASP.NET
Create GridView through drag and drop from the Toolbox
An easy approach to creating a GridView is to drag and drop GridView from Toolbox.
Create GridView In XML
You can also create GridView in your XML file by using GridView tag.
<asp:GridView ID="GridView2" runat="server">
Populating GridView Through SQL Server Express
GridView in ASP.NET provides a facility to add data through it’s automatically created DataSet from SQL database by following simple steps. To populate GridView through SQL Server database, you must have SQL server configured and installed and a database is having a table, which you want to show in GridView. You can also populate GridView in C#.
1. New Data Source from GridView Tasks
Open GridView Tasks to add SQL Server data source. Click on <new data source..> from Choose Data Source drop-down.
2. Choose Data Source for GridView in ASP.NET
Data Source configuration wizard will appear, choose Data Source Type i.e. SQL Database. Specify an Id and click OK.
3. Configure Data Source
A dialog box will appear asking for the connection string. If you don’t have any preconfigured data source connection, create a New Connection.
New Connection dialog box will appear.
Enter Server Name. If you don’t know the server name, you can get it from SQL server, which is displayed while connecting SQL server.
Enter the server name and choose the database from which you want to get data. Click on Test Connection to check the connection between your application and data source i.e. SQL server. Click Ok to Add the newly created connection.
Your GridView is now successfully connected to your database. Click Next to move to the next step.
4. Save Connection for Future Use
A dialog box will appear to save connection for future use. Click Next to move to the next step.
5. Specify Table to be Displayed in GridView
Choose the table from which you want to get data for GridView from the drop down menu in Configure Data Source dialog box. Choose columns from the check boxes below, to be displayed in GridView check * for all the columns. Click next to preview configured GridView.
6. Test Configured GridView Data
Click on test query to view the data received from data source i.e. SQL Server database. Click Finish to complete the process of adding a source for GridView.
You GridView is now configured.
Get Selected Row Data from GridView in ASP.net
To get data from a particular row when the user clicks on it, then you must implement
From Properties -> Events of the GridView you should bind events as in your .cs file if you created manually. Or you can also get auto-generated methods by double clicking on RowDataBound and SelectedIndexChanged in the Event properties of GridView.
Click Event Handler for GridView Rows
Set ToolTip for a row on mouse over
If you want to show some text on mouse over you can use
row.ToolTip = "Some Text";
To implement click listener for GridView row as when the user clicks anywhere on a row. Implement RowDataBound method with sender object and GridViewRowEventArgs object as parameters.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow) //check if Row type is a data row
//Implement onclick by using post back method
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
//setting tool tip
e.Row.ToolTip = "Click to select this row.";
Get Data from the Selected Row of GridView in ASP.NET
Change the color of row on mouse click
If you want to change the color of the row when the user clicks on it, you can use
ColorTranslator.FromHTML("# HTML_color_code"). (import for
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
To get the data when the selected row is changed i.e. user selects any other row. Implement OnSelectedIndexChanged() with sender object and EventArgs object as parameters.
protected void OnSelectedIndexChanged(object sender, EventArgs e)
foreach (GridViewRow row in GridView1.Rows) //for all the rows in the GridView
if (row.RowIndex == GridView1.SelectedIndex) //check if the current rows is the selected row
row.BackColor = ColorTranslator.FromHtml("#A1DCF2"); //change the background color of row
row.ToolTip = string.Empty; //set selected row tool tip to empty
if (!GridView1.SelectedRow.Cells.Text.ToString().Equals(null)) //check if the first column of selected row is null
//GridView.SelectedRow.Cells.Text.ToString(); returns the text of first column of the selected row
selectedId.Text = GridView1.SelectedRow.Cells.Text.ToString(); //do or display the text to a label
row.BackColor = ColorTranslator.FromHtml("#FFFFFF"); //when row not selected set background color to white
row.ToolTip = "Click to select this row."; //set some desired text on tool tip
Event Validation Error
As this method use postback call, It will give event validation error.
Server Error in '/' Application.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation=”true”/> in configuration or <%@ Page EnableEventValidation=”true” %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Stack Trace of Error
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +9732594
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +32
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9654230
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639
Easy way to disable event validation
You can disable event validation by modifying the header of the aspx file, by placing a simple property in the source of aspx file
And the complete header of the file containing GridView will look like
<%@ Page Language="C#" AutoEventWireup="true" ClientTarget="uplevel" CodeBehind="GridViewDemoForm.aspx.cs" Inherits="GridViewDemo.GridViewDemoForm" EnableEventValidation="true" %>
Disadvantage of setting EnableEventValidation to false
Event validation provides the security level for injection attacks but in this case, the user only clicks on the GridView row so setting event validation to false doesn’t matter.
There are alternate ways you can pass the event validation like by using UpdatePanel.
Hope you like this tutorial, Stay Tuned! Stay Blessed!
Don’t forget to give your feedback through comments. chears!