C# 我可以以编程方式将链接按钮添加到 gridview 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1039474/
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
Can I programmatically add a linkbutton to gridview?
提问by pschorf
I've been looking through some similar questions without any luck. What I'd like to do is have a gridview which for certain items shows a linkbutton and for other items shows a hyperlink. This is the code I currently have:
我一直在寻找一些类似的问题,但没有任何运气。我想要做的是有一个 gridview,它对于某些项目显示一个链接按钮,而对于其他项目则显示一个超链接。这是我目前拥有的代码:
public void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var data = (FileDirectoryInfo)e.Row.DataItem;
var img = new System.Web.UI.HtmlControls.HtmlImage();
if (data.Length == null)
{
img.Src = "/images/folder.jpg";
var lnk = new LinkButton();
lnk.ID = "lnkFolder";
lnk.Text = data.Name;
lnk.Command += new CommandEventHandler(changeFolder_OnCommand);
lnk.CommandArgument = data.Name;
e.Row.Cells[0].Controls.Add(lnk);
}
else
{
var lnk = new HyperLink();
lnk.Text = data.Name;
lnk.Target = "_blank";
lnk.NavigateUrl = getLink(data.Name);
e.Row.Cells[0].Controls.Add(lnk);
img.Src = "/images/file.jpg";
}
e.Row.Cells[0].Controls.AddAt(0, img);
}
}
where the first cell is a TemplateField. Currently, everything displays correctly, but the linkbuttons don't raise the Command event handler, and all of the controls disappear on postback.
其中第一个单元格是 TemplateField。目前,一切都显示正确,但链接按钮不会引发命令事件处理程序,并且所有控件在回发时都会消失。
Any ideas?
有任何想法吗?
采纳答案by Cerebrus
I think you should try forcing a rebind of the GridView uponpostback. This will ensure that any dynamic controls are recreated and their event handlers reattached. This should also prevent their disappearance after postback.
我认为您应该尝试在回发时强制重新绑定 GridView 。这将确保重新创建任何动态控件并重新附加它们的事件处理程序。这也应该防止它们在回发后消失。
IOW, call DataBind()
on the GridView upon postback.
IOW,DataBind()
在回发时调用GridView。
回答by Chris Mullins
Why don't you create the button declaratively, and create the hypen declaratively (using a literal control) and then using data binding syntax and set the visibility that is Visible property of the controls to true or false as needed:
为什么不以声明方式创建按钮,并以声明方式创建连字符(使用文字控件),然后使用数据绑定语法并根据需要将作为控件的 Visible 属性的可见性设置为 true 或 false :
Visible='<%#((FileDirectoryInfo)Container.DataItem).Length == null) %>'
Something like that.
类似的东西。
回答by Mohsin Naeem
You can also add these in the Row_Created event and then you don't have to undo !PostBack check
您也可以在 Row_Created 事件中添加这些,然后您不必撤消 !PostBack 检查