在gridview(而不是datagridview)asp.net中获取单击的单元格索引

本文关键字:获取 net 单击 索引 单元格 asp gridview datagridview | 更新日期: 2023-09-27 18:00:58

当我单击网格视图(而不是数据网格视图(中的单元格时,我想要获得单元格索引(而不是行索引(,而不是行指数。我使用asp.net-c#

在gridview(而不是datagridview)asp.net中获取单击的单元格索引

使用RowCreated事件注册一个单元格,点击每个单元格并处理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是一个隐藏字段,它是在aspx上以声明方式添加的,用于存储所选索引:

<asp:HiddenField ID="SelectedGridCellIndex" runat="server" Value="-1" />
<asp:GridView ID="GridView1" runat="server" 
    OnRowCreated="OnRowCreated" 
    OnSelectedIndexChanged="SelectedIndexChanged" 
    OnRowDataBound="OnRowDataBound" AutoGenerateColumns="false">
   <Columns>
     .....

您需要禁用此页面的事件验证,否则ASP.NET会抱怨:

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="Grid.aspx.cs" Inherits="CSharp_WebApp.Grid" %>