C# Get the row index of a GridView by clicking a cell

All we need is an easy explanation of the problem, so here it is.

I have this GridView:

<asp:GridView ID="gvTabelaTeste" runat="server" AutoGenerateColumns="false" CssClass="w3-table w3-striped w3-white w3-hoverable w3-centered" OnRowDataBound="gvTabelaTeste_RowDataBound">
    <asp:BoundField DataField="Status" HeaderText="Status"/>
    <asp:BoundField DataField="Atividade" HeaderText="Atividade"/>
    <asp:BoundField DataField="Analista" HeaderText="Analista"/>
    <asp:BoundField DataField="DtInicial" HeaderText="Data de abertura"/>
    <asp:BoundField DataField="DtFinal" HeaderText="Data de validade"/>

and this two divs:

<div id="light" class="white_content">
  <h6 style="background-color: lightgray; margin-bottom: 0; margin-top: 0; text-align: center;"><strong>Escolher nova data de validade</strong></h6>
  <asp:Calendar ID="Calendario" runat="server" OnSelectionChanged="Calendario_SelectionChanged"></asp:Calendar>
<div id="fade" class="black_overlay"></div>

I put this code on RowDataBound event from the GridView:

e.Row.Cells[4].Attributes["onclick"] = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block';";

So, when I click on the cell 4 of every row, it changes the style display of the divs, to make it similar to a popup.
Inside the div I have a Calendar, that contains this code on SelectionChanged event:

gvTabelaTeste.Rows[/*here should be the row index*/].Cells[4].Text = Calendario.SelectedDate.ToShortDateString();

What I’m trying to do is change the text of the clicked cell to the selected date on the calendar, but the problem is that I can’t get the index of the row of the cell that was clicked.

How can I do that? I’ve tried different methods, but until now no one worked for me.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I believe you shoud first "select" row in a GridView. After that it is easy.


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CalendarApp._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="OnSelectedIndexChanged">
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>

Code behind

    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;

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

    protected void OnSelectedIndexChanged(object sender, EventArgs e)
        selectedIndex = GridView1.SelectedIndex;
        foreach (GridViewRow row in GridView1.Rows)
            if (row.RowIndex == GridView1.SelectedIndex)
                row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
                row.ToolTip = string.Empty;
                row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
                row.ToolTip = "Click to select this row.";

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text = Calendar1.SelectedDate.ToString("d");

Borrowed and adapted for you from: https://www.aspsnippets.com/Articles/Selecting-GridView-Row-by-clicking-anywhere-on-the-Row.aspx

Method 2

The how to get the rowIndex has been answered here: WPF- How to get selected row index in datagrid?

See if this fits your needs.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply