【发布时间】:2011-10-18 23:49:26
【问题描述】:
背景:
我有一个 GridView,它通过 DataSourceID 从 SqlDataSource 填充。这些行显示来自 SQL 视图的一些摘要数据。单击一行后,我想将我的用户带到另一个带有 DetailsView 控件的页面,该控件填充了与单击的行相关的数据库中的完整值集。我的用户应该能够编辑数据,下载与记录关联的文件,并根据所述数据创建不同类型的新记录。
错误:
我为 Clickable GridView 行找到的所有示例最终都会出现错误 Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. 的一些变体
当然,我不想通过禁用事件验证将我的网站暴露给漏洞。我需要能够获取单击行的关联记录的主键,并可能通过 DetailsView 在后续页面上对该数据执行操作。我怀疑我的错误是我的设置造成的,这就是我包含这些详细信息的原因。
我的问题是:
- 如何捕获点击行的主键?
- 如何在单击时转到“详细信息”页面,其中包含来自被单击行记录的数据的预填表单?
这是完整的解决方案
**再次感谢伊卡洛斯的帮助
'Fetch the DataKey ("ID"), seems to work
Protected Sub RowBind(ByVal sender As Object, ByVal e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim datakey As String = GridView1.DataKeys(e.Row.RowIndex).Value.ToString()
End If
End Sub
'Handle button click
Protected Sub RowClick(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) _
Handles GridView1.RowCommand
If e.CommandName = "Select" Then
'Add to session variable; translate the index of clicked to Primary Key
Session.Add("DetailsKey", GridView1.DataKeys(e.CommandArgument).Value.ToString)
Response.Redirect("details.aspx")
End If
End Sub
还有我的标记
<asp:GridView ID="GridView1" runat="server" DataSourceID="GridView1SDS"
DataKeyNames="ID" AllowPaging="True" AllowSorting="True">
'<!-- Styling -->
<Columns>
<asp:ButtonField ButtonType="Button" Text="Details" CommandName="Select" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="GridView1SDS" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="select * from viewRequestQueue">'<!-- An SQL View -->
</asp:SqlDataSource>
转发页面 VB 和标记
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GridView2SDS.SelectCommand = "select * from viewRequestQueue where ID = " _
+ Session.Item("DetailsKey").ToString
End If
End Sub
<asp:DetailsView ID="GridView2" runat="server" DataSourceID="GridView2SDS">
'<!-- Styling -->
</asp:DetailsView>
<asp:SqlDataSource ID="GridView2SDS" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>">
</asp:SqlDataSource>
另外,请注意,如果您的 DataSource 的 SelectCommand 在代码隐藏中处理,这意味着 DataBind 将覆盖标记中的 <Columns>。要解决这个问题,您应该在 DataBind 之前的代码中定义列。所以说我想在我的转发页面中添加另一个 ButtonField 列(注意标记中没有提供 SelectCommand),我在设置 SelectCommand 并执行 DataBind 之前添加了以下内容:
Dim id As New ButtonField()
id.ButtonType = ButtonType.Button
id.Text = "Load"
id.CommandName = "Select"
PubDetails.Columns.Add(id)
【问题讨论】:
-
你熟悉 GridView 的 DataKeys 属性吗?
-
@TheGeekYouNeed:只有我在 API 中读到的内容,不多。我不知道如何在代码中实现它>.
标签: asp.net vb.net gridview detailsview