Thursday, April 5, 2018

Selecting GridView Row by clicking anywhere on the Row

In this article I will explain how to select GridView Row when mouse is clicked anywhere on the GridView Row in ASP.Net.

HTML Markup
The HTML Markup consists of an ASP.Net GridView with two columns and a Dummy LinkButton. The Dummy LinkButton is used, so that the ASP.Net __doPostBack JavaScript function is rendered as we will require it for Row Selection.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound" OnSelectedIndexChanged = "OnSelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
<asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
Namespaces
You will need to import the following namespaces
C#
using System.Data;
using System.Drawing;
VB.Net
Imports System.Data
Imports System.Drawing
Binding the GridView
The GridView is populated using some dummy records using DataTable.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "John Hammond""United States");
        dt.Rows.Add(2, "Mudassar Khan""India");
        dt.Rows.Add(3, "Suzanne Mathews""France");
        dt.Rows.Add(4, "Robert Schidner""Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "John Hammond""United States")
        dt.Rows.Add(2, "Mudassar Khan""India")
        dt.Rows.Add(3, "Suzanne Mathews""France")
        dt.Rows.Add(4, "Robert Schidner""Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
Select GridView Row on mouse click event in ASP.Net
In the OnRowDataBound event handler, for each GridView Row a JavaScript click event handler is attached using the onclick attribute. The GetPostBackClientHyperlink method accepts the GridView instance as well as the command with the Row Index of the Row.
Note: GetPostBackClientHyperlink when rendered this gets converted to the JavaScript __doPostBack method that we were discussing earlier.
Doing the above makes each GridView Row clickable and also it executes the OnSelectedIndexChanged event handler (discussed below) when clicked.
C#
protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
        e.Row.ToolTip = "Click to select this row.";
    }
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Attributes("onclick") = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" & e.Row.RowIndex)
        e.Row.ToolTip = "Click to select this row."
    End If
End Sub
The OnSelectedIndexChanged event handler
Below is the OnSelectedIndexChanged event handler which will be triggered when the GridView Row is clicked. When any GridView row is clicked the background color of the Selected GridView Row is changed using the following code, to know more about it please refer my article How to change GridView Selected Row Color in ASP.Net
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowIndex == GridView1.SelectedIndex)
        {
            row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
            row.ToolTip = string.Empty;
        }
        else
        {
            row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
            row.ToolTip = "Click to select this row.";
        }
    }
}
VB.Net
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
    For Each row As GridViewRow In GridView1.Rows
        If row.RowIndex = GridView1.SelectedIndex Then
            row.BackColor = ColorTranslator.FromHtml("#A1DCF2")
            row.ToolTip = String.Empty
        Else
            row.BackColor = ColorTranslator.FromHtml("#FFFFFF")
            row.ToolTip = "Click to select this row."
        End If
    Next
End Sub
  
 
Handling the Event Validation Error
Since we are attaching the event directly to the GridView Row which by default does not have any OnClick event, you might land into the following error.
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.
To resolve the above error you must set the property EnableEventValidation = "false"
in the @Page Directive as shown below

source : https://www.aspsnippets.com/Articles/Selecting-GridView-Row-by-clicking-anywhere-on-the-Row.aspx

No comments:

Post a Comment