你如何绑定你的GridView
?您使用数据源控件吗?如果您在期间手动绑定Page_Load
,由于网格绑定每个往返,事件处理程序可能无法正确捕获。如果是这种情况,您可能想尝试以下操作:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
您可以发布示例绑定代码来配合您的标记吗?
If you really想要强制解决此问题,您可以挂钩网格上的 RowDataBound 事件,手动找到按钮并在后面的代码中添加处理程序。就像是:
标记片段:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
后面的代码:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
我不确定该按钮的用途是什么,但假设它是一个行删除按钮,您可能不想在事件处理程序中采用这种方法,您无法直接访问有问题的行,例如你会使用RowCommand
event.
您使用模板字段有什么原因吗? VS 说一个ButtonField
?如果您使用ButtonField
,然后你可以挂入RowCommand
event.
标记片段:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
后面的代码:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
您可能需要查阅有关以下某些主题的 MSDN 文档:
- 行命令事件 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
- ButtonField 类 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield.aspx
EDIT:
回答您关于 ButtonField 的问题 - 是的,我不明白为什么您仍然不能处理按钮字段。这是一个在行数据绑定期间查找按钮字段并隐藏它的片段(未经测试,但我认为会起作用......)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}