【问题标题】:Asp.Net GridView Click Row Redirect to URLAsp.Net GridView 单击行重定向到 URL
【发布时间】:2018-03-05 02:05:39
【问题描述】:

我有一个 ASP.Net 数据绑定的 GridView,我希望在单击一行时打开一个传递所选行 ID 的 URL。 ID 是数据库表中的一列,但是我不想向用户显示它。

如果我将 ID 列的可见性设置为 false,它不会用数据填充该列。即e.Row.Cells[0].Text 返回一个空字符串。

以下代码正在运行,但我想使用 ID 列不显示。

在 .aspx 文件中:

<asp:GridView 
                id="GridViewTest"
                runat="server" 
                DataSourceID="sqlSource" 
                AutoGenerateColumns="false"
                OnRowDataBound="GridViewTest_RowDataBound"
                >
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID"/>
                <asp:BoundField DataField="DisplayName" HeaderText="Name" />
            </Columns>
            </asp:GridView>

在 .cs 文件中:

protected void GridViewTest_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onclick"] = $"location.href = 'default.aspx?appID={e.Row.Cells[0].Text}'";
            e.Row.Attributes["style"] = "cursor:pointer";
        }
    }

【问题讨论】:

  • 为什么不用itemtemplate?如果不想显示ID,可以加一个style属性display:none
  • 更新了我的答案(再次)。

标签: c# asp.net gridview


【解决方案1】:

确保您选择了正确的单元格。例如,如果我显示“选择”和“编辑”按钮,我必须获得第三个单元格:

txtbox.Text = e.Row.Cells[2].Text;

或者,您需要将 ID 字段转换为模板字段,从而创建一个您可以找到的控件。

// get the label inside the ItemTemplate.
Label lbl = (Label)e.Row.Cells[0].FindControl("Label1");

// get the label's text and put it into a textbox.
txtbox.Text = lbl.Text;

【讨论】:

  • 这绝对是正确的单元格。 Cells[0] 为空白,Cells[1] 有下一项的内容。如果该字段可见,则 Cells[0] 有效。如果可见字段设置为 false,则它只是空的。
  • 您是否将其设为模板字段?在设计视图中,gridview 任务 > 编辑列 > 选择左侧的列 > 将此字段转换为模板(右侧链接)。
  • 一个模板字段有同样的问题,如果我用css隐藏它,虽然我现在想出了如何去做,发布了答案。虽然不确定这是否是最好的方法。
【解决方案2】:

为了解决这个问题,我将 DataKeyNames 属性设置为我想使用的数据库表列的名称,在本例中为 ID。

    <asp:GridView 
                    id="GridViewTest"
                    runat="server" 
                    DataSourceID="sqlSource" 
                    AutoGenerateColumns="false"
                     OnRowDataBound="GridViewAppInstallCount_RowDataBound"
                    DataKeyNames="ID"
                    >
<Columns>
    <asp:BoundField DataField="DisplayName" HeaderText="Name" />
</Columns>
  </asp:GridView>

使用此代码检索值:

protected void GridViewTest_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onclick"] = $"location.href = 'default.aspx?appID={GridViewTest.DataKeys[e.Row.RowIndex]["ID"]}'";
            e.Row.Attributes["style"] = "cursor:pointer";
        }
    }

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 2014-07-23
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多