c# gridview 行点击

标签 c# gridview click

当我单击 GridView 中的一行时,我想使用从数据库中获取的 ID 转到另一个页面。

在我的 RowCreated 事件中,我有以下行:

e.Row.Attributes.Add(
     "onClick",
     ClientScript.GetPostBackClientHyperlink(
          this.grdSearchResults, "Select$" + e.Row.RowIndex));

为了防止出现错误消息,我有以下代码:

protected override void Render(HtmlTextWriter writer)
{
    // .NET will refuse to accept "unknown" postbacks for security reasons. 
    // Because of this we have to register all possible callbacks
    // This must be done in Render, hence the override
    for (int i = 0; i < grdSearchResults.Rows.Count; i++)
    {
        Page.ClientScript.RegisterForEventValidation(
                new System.Web.UI.PostBackOptions(
                    grdSearchResults, "Select$" + i.ToString()));
    }
    // Do the standard rendering stuff
    base.Render(writer);
}

我怎样才能给一行一个唯一的 ID(来自数据库),当我点击该行时,会打开另一个页面(就像点击 href)并且该页面可以读取 ID。

最佳答案

马丁,

这是另一个带有一些漂亮的行突出显示和 href 样式光标的示例:

protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");
    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
    e.Row.Attributes.Add("style", "cursor:pointer;");
    e.Row.Attributes.Add("onclick", "location='patron_detail.aspx?id=" + e.Row.Cells[0].Text + "'");
  }
}

以上代码适用于 .NET 3.5。但是,您不能将 id 列设置为 Visible="false",因为您的 id 键将得到一个空白查询字符串值:

<asp:GridView ID="gvSearch" runat="server" OnRowDataBound="gvSearch_RowDataBound" AutoGenerateColumns="false">
  <Columns>
    <asp:BoundField DataField="id" Visible="false" />
    <asp:BoundField DataField="first_name" HeaderText="First" />
    <asp:BoundField DataField="last_name" HeaderText="Last" />
    <asp:BoundField DataField="email" HeaderText="Email" />
    <asp:BoundField DataField="state_name" HeaderText="State" />
  </Columns>
</asp:GridView>

因此将第一列改为:

<asp:BoundField DataField="id" ItemStyle-CssClass="hide" />

将此 css 添加到页面顶部:

<head>
  <style type="text/css">
    .hide{
      display:none;
    }
  </style>
<head>

但要隐藏标题行的第一个单元格,请将其添加到代码隐藏中的 gvSearch_RowDataBound() 中:

if (e.Row.RowType == DataControlRowType.Header)
{
  e.Row.Cells[0].CssClass = "hide";
}

显然,您也可以在代码隐藏中隐藏 id 列,但这会导致标记中的文本多于 css 类:

e.Row.Cells[0].Attributes.Add("style", "display:none;");
e.Row.Attributes.Add("style", "cursor:pointer;");

关于c# gridview 行点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/331231/

相关文章:

c# - ZedGraph 实时数据绘图 C#

c# - 使用 http :\\URL 的 WPF 图像 UriSource 和数据绑定(bind)

c# - 使用绑定(bind)数据集中的值设置 Gridview 行背景颜色

Android Glide 图像加载库显示模糊图像

Angular 6 with Material,点击事件无法正常工作

c# - C#和android应用程序之间的RPC通信

c# - 高效地更新 .NET 字典中的绑定(bind)

c# - ASP.NET 为整行数据表/ GridView 添加超链接

javascript - 模拟不同选择器的点击事件

javascript - 在输入文本字段上按 Enter 键提交表单