如何通过HyperLinkField传递代码后台变量

5

这是我的 C# 代码后端。

protected void Page_Load(object sender, EventArgs e)
    {
           Name = "Nitin";                      
    } 

我有一个GridView,其中包含一个Hyperlinkfield。我想通过HyperLinkField从C#页面(在代码后台中)将Name发送到下一页,但它不是GridView的BoundField之一(即我从EntityDataSource获取的字段)。这是我的asp.net代码。

代码:

   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="WorkItemsEntityDataSource">
    <Columns>
        <asp:hyperlinkfield datatextfield="Id"                    
                datanavigateurlfields="Id"
                datanavigateurlformatstring="~\WorkItems.aspx?Id={0}"          
                headertext="Id"/> 
        <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
        <asp:BoundField DataField="TFSId" HeaderText="TFSId" SortExpression="TFSId" />
        <asp:CheckBoxField DataField="IsBillable" HeaderText="IsBillable" SortExpression="IsBillable" />
    </Columns>
</asp:GridView>

请发布您的网格视图代码并清楚地阐述您的问题。 - Amit Singh
4个回答

4
您可以像这样从后端传递导航URL:
在Aspx页面中:
              <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="hyp" runat="server" Text="Navigation"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>    

在代码后台类中,像这样绑定用户网格视图数据的事件:
protected void grddata_RowDataBound(object sender, GridViewRowEventArgs e)
    {    
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int ID = Convert.Int32(DataBinder.Eval(e.Row.DataItem, "ID"));
            HyperLink hyp = (HyperLink)e.Row.FindControl("hyp");
            hyp.NavigateUrl = "Test.aspx?Name='" + Request.QueryString["test"] + "'&&ID"+ ID +"";
        }
    }

我想这会对您有所帮助...

嗨Rajpurohit,我想知道如何通过HyperLinkField发送绑定字段GridView中的Id和Name。 - Nitin Maheshwari

0

我其实不确定在数据绑定控件中使用它是否可行,但是你正在构建的 URL 明显不包含查询字符串参数“Name”。应该像这样:

~\WorkItems.aspx?Id={0}&Name={1}

如果不需要Id,只需将Id替换为Name:

~\WorkItems.aspx?Name={0}

关于替换 - 我不知道您的数据对象具有什么属性以及如何绑定到它们。我认为您没有问题,因为绑定到Id可以工作(可能)。

更新

如果从数据源中未返回Name,则应创建包含Name字段的新实体,或者使用一些常量名称,例如在页面中声明的名称(不确定是否应在每行中显示相同的名称)。 第二个选项可以这样实现:

~\WorkItems.aspx?Id={0}&Name=<%= Name %>

实际上,我从EntityDataSource获取的不是Name,而是后台代码变量。所以,如果您知道如何发送它,请回复。任何帮助都将不胜感激。 - Nitin Maheshwari
发布了一个关于将服务器变量嵌入ASP页面的更新。 - Sasha

0

您可以使用:

<asp:TemplateField HeaderText="test">
     <ItemTemplate>
           <asp:HyperLink runat="server" ID="temp" NavigateUrl='<%# String.Format("~\WorkItems.aspx?Id={0}&Name={1}",  Eval("Name"), Name)%>' ></asp:HyperLink>
      </ItemTemplate>
</asp:TemplateField>

0
您可以通过以下方式修改HyperLinkField的URL:
protected void pendingAccountsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((HyperLink) e.Row.Cell[0].Controls[0]).NavigateUrl = "http://stackoverflow.com";
    }
}

只需更改为指定e.Row.Cell[0]中的正确索引即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接