You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在循环中获取DataGrid中HyperLinkColumn的DataNavigateUrlField?

如何在DataGrid循环中获取HyperLinkColumn的DataNavigateUrlField对应值

我在DataGrid控件中添加了HyperLinkColumn,需要通过for循环获取它的DataNavigateUrlField对应的数据值。已经掌握通过ID获取asp:label控件文本的方法,想请教如何实现这个需求。

我的DataGrid代码

<asp:DataGrid id="MyDataGrid" 
   BorderColor="black"
   BorderWidth="1"
   GridLines="Both"
   AutoGenerateColumns="false"
   runat="server">

 <HeaderStyle BackColor="#aaaadd"/>

 <Columns>

    <asp:HyperLinkColumn
         HeaderText="Select an Item"
         DataNavigateUrlField="IntegerValue"
         DataNavigateUrlFormatString="detailspage.aspx?id={0}"
         DataTextField="PriceValue"
         DataTextFormatString="{0:c}"
         Target="_blank"/>
   <asp:BoundColumn DataField="Type" HeaderText="Type"   />
 </Columns>

</asp:DataGrid>

我的现有代码

For Each item As DataGridItem In MyDataGrid.Items           
    Dim cell As Hyperlink = CType(item.Cells(0).Controls(0), Hyperlink)
Next

解决方案

你的现有代码已经正确获取到了单元格中的HyperLink控件,接下来可以通过两种方式获取DataNavigateUrlField对应的IntegerValue值:

方法1:解析HyperLink的NavigateUrl参数

通过解析生成后的URL,提取其中的id参数值(对应IntegerValue):

For Each item As DataGridItem In MyDataGrid.Items           
    Dim cell As HyperLink = CType(item.Cells(0).Controls(0), HyperLink)
    ' 解析URL中的查询参数
    Dim queryParams As NameValueCollection = HttpUtility.ParseQueryString(New Uri(cell.NavigateUrl).Query)
    Dim integerValue As String = queryParams("id")
    ' 此处可使用integerValue变量进行后续操作
Next

方法2:直接从绑定的数据源获取

从DataGridItem绑定的数据源对象中直接读取IntegerValue字段,这种方式更直接,不依赖URL格式:

For Each item As DataGridItem In MyDataGrid.Items           
    ' 仅处理数据行,跳过表头、脚注等非数据行
    If item.ItemType = ListItemType.Item OrElse item.ItemType = ListItemType.AlternatingItem Then
        ' 假设数据源是DataRowView,根据实际数据源类型调整
        Dim dataItem As DataRowView = CType(item.DataItem, DataRowView)
        Dim integerValue As String = dataItem("IntegerValue").ToString()
        ' 此处可使用integerValue变量进行后续操作
    End If
Next

两种方法对比

  • 方法1:依赖DataNavigateUrlFormatString的格式,若后续URL格式修改,解析逻辑需同步调整,但无需关注数据源类型。
  • 方法2:不依赖URL格式,获取数据更直接,但需要明确数据源的类型(如DataRowView、自定义实体类等)。

内容的提问来源于stack exchange,提问作者user819774

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:58:18