【问题标题】:Get clicked cell index in gridview (not datagridview) asp.net在gridview(不是datagridview)asp.net中获取单击的单元格索引
【发布时间】:2015-09-21 01:31:21
【问题描述】:

当我单击 gridview(不是 datagridview)中的单元格时,我想获取单元格索引(不是行索引),而不是行索引。我使用 asp.net - c#

【问题讨论】:

  • ASP.NET 中没有DataGridView,所以你真的指的是 ASP.NET?
  • 就像我写gridview(不是datagridview)
  • 如果你写了“gridview(not datagrid)”会很有意义,否则信息是多余的,因为 ASP.NET 不是 winforms。但我明白了。
  • 我写这个是因为我写了类似的问题并且我有 datagridview 的答案

标签: c# asp.net gridview


【解决方案1】:

使用RowCreated事件注册每个单元格上的单元格点击并处理GridView'sSelectedIndexChangedEvent

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

【讨论】:

  • 感谢您的回复,但是 SelectedIndexChangedEvent 中应该写什么呢?
  • @zvonnkko:现在我已经测试过了,你需要一个稍微不同的方法。看看我编辑的答案。
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 2011-03-11
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多