When I click cell in gridview (not datagridview) I want to get cell index (not row index), not row index. I use asp.net - c#
Asked
Active
Viewed 4,758 times
2
-
In `ASP.NET` there is no `DataGridView`, so are you really referring to ASP.NET? – Tim Schmelter Jul 03 '15 at 09:11
-
like I write gridview (not datagridview) – zvonnkko Jul 03 '15 at 09:13
-
Would make sense if you wrote "gridview(not datagrid)", otherwise the informations is redundant since ASP.NET is not winforms. But i get it. – Tim Schmelter Jul 03 '15 at 09:14
-
I wrote that because I wrote similar question and I had answer for datagridview – zvonnkko Jul 03 '15 at 09:17
1 Answers
4
Use the RowCreated
event to register a cell-click on each cell and handle the GridView's
SelectedIndexChangedEvent
:
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++ )
{
TableCell cell = e.Row.Cells[i];
cell.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
cell.Attributes["onmouseout"] = "this.style.textDecoration='none';";
cell.ToolTip = "You can click this cell";
cell.Attributes["onclick"] = string.Format("document.getElementById('{0}').value = {1}; {2}"
, SelectedGridCellIndex.ClientID, i
, Page.ClientScript.GetPostBackClientHyperlink((GridView)sender, string.Format("Select${0}", e.Row.RowIndex)));
}
}
}
protected void SelectedIndexChanged( Object sender, EventArgs e)
{
var grid = (GridView) sender;
GridViewRow selectedRow = grid.SelectedRow;
int rowIndex = grid.SelectedIndex;
int selectedCellIndex = int.Parse(this.SelectedGridCellIndex.Value);
}
SelectedGridCellIndex
is a hidden-field which is added declaratively on the aspx to store the selected index:
<asp:HiddenField ID="SelectedGridCellIndex" runat="server" Value="-1" />
<asp:GridView ID="GridView1" runat="server"
OnRowCreated="OnRowCreated"
OnSelectedIndexChanged="SelectedIndexChanged"
OnRowDataBound="OnRowDataBound" AutoGenerateColumns="false">
<Columns>
.....
You need to disable event-validation for this page, otherwise ASP.NET complains:
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="Grid.aspx.cs" Inherits="CSharp_WebApp.Grid" %>

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
Thank You for your reply, but what should I write in SelectedIndexChangedEvent? – zvonnkko Jul 03 '15 at 09:37
-
@zvonnkko: now i have tested it, you need a lightly different approach. have a look at my edited answer. – Tim Schmelter Jul 03 '15 at 09:46
-
@Tim Schmelter I followed your instruction but nowhere I click on GridView, selectedCellIndex returns value of -1? – Jovica May 02 '22 at 08:45