本文介绍了获取单击的单元格指数的GridView(不datagridview的)asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击GridView中(不datagridview的)我想要得到的细胞指数(未行索引),而不是排索引单元。我使用asp.net - C#

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#

推荐答案

使用 RowCreated 事件注册一个在每个单元细胞单击并办理 GridView的 SelectedIndexChangedEvent

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 这是声明方式添加的ASPX存储选定索引的隐藏字段:

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

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

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" %>

这篇关于获取单击的单元格指数的GridView(不datagridview的)asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 01:17