C# 如何将超链接添加到动态 gridview 列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1819381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a Hyperlink to a dynamic gridview column
提问by Avi
I have an issue hope someone can help.
我有一个问题希望有人可以提供帮助。
I have a dynamic Gridview
. I need to have a hyperlink
on gridview column. These hyperlink should open a popup to display certain data on clicking.
我有一个动态Gridview
. 我需要hyperlink
在 gridview 列上。这些超链接应打开一个弹出窗口以在单击时显示某些数据。
I tried this by having a dynamic template field . But even on binding the data , I'm unable to get the hyper link for the column. I'm able to get the data but not the hyperlink.
我通过有一个动态模板字段来尝试这个。但即使绑定数据,我也无法获得该列的超链接。我能够获取数据,但不能获取超链接。
This is the HyperLinkTemplate
class which is implementing ITemplate
.
这是HyperLinkTemplate
正在实现的类ITemplate
。
public class HyperLinkTemplate : ITemplate
{
private string m_ColumnName;
public string ColumnName
{
get { return m_ColumnName; }
set { m_ColumnName = value; }
}
public HyperLinkTemplate()
{
//
// TODO: Add constructor logic here
//
}
public HyperLinkTemplate(string ColumnName)
{
this.ColumnName = ColumnName;
}
public void InstantiateIn(System.Web.UI.Control ThisColumn)
{
HyperLink HyperLinkItem = new HyperLink();
HyperLinkItem.ID = "hl" + ColumnName;
HyperLinkItem.DataBinding += HyperLinkItem_DataBinding;
ThisColumn.Controls.Add(HyperLinkItem);
}
private void HyperLinkItem_DataBinding(object sender, EventArgs e)
{
HyperLink HyperLinkItem = (HyperLink)sender;
GridViewRow CurrentRow = (GridViewRow)HyperLinkItem.NamingContainer;
object CurrentDataItem = DataBinder.Eval(CurrentRow.DataItem, ColumnName);
HyperLinkItem.Text = CurrentDataItem.ToString();
}
}
采纳答案by Dr. Wily's Apprentice
I'm not entirely sure that I understand what you are trying to accomplish, but I don't think that you should have to build your own template class for this.
我不完全确定我了解您要完成的任务,但我认为您不必为此构建自己的模板类。
You might mean something other than what I'm thinking by the term "dynamic gridview", but if you need to add a hyperlink to each row of a column in a GridView, and if you need to do this in the code-behind, then I would suggest handling the GridView's RowDataBound event and doing something like the following in the event handler:
您的意思可能与我所说的“动态网格视图”一词不同,但是如果您需要向 GridView 中的每一列添加一个超链接,并且如果您需要在代码隐藏中执行此操作,那么我建议处理 GridView 的 RowDataBound 事件并在事件处理程序中执行如下操作:
protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink link = new HyperLink();
link.Text = "This is a link!";
link.NavigateUrl = "Navigate somewhere based on data: " + e.Row.DataItem;
e.Row.Cells[ColumnIndex.Column1].Controls.Add(link);
}
}