你是如何绑定你的GridView的?您是否使用数据源控件?如果您在Page_Load 期间手动绑定,则可能由于网格每次往返都绑定,事件处理程序没有正确捕获。如果是这种情况,您可能想尝试以下方法:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
您能否发布示例绑定代码以配合您的标记?
如果您真的想要强制执行该问题,您可以挂钩到 Grid 上的 RowDataBound 事件,手动找到按钮并在后面的代码中添加处理程序。比如:
标记sn-p:
<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 事件一样。
您使用“模板”字段是否有原因?与说ButtonField?如果您使用ButtonField,则可以挂钩RowCommand 事件。
标记sn-p:
<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 文档,了解其中一些主题:
编辑:
回答您关于 ButtonField 的问题 - 是的,我不明白为什么您仍然不能处理按钮字段。这是一个 sn-p,用于在绑定行数据期间找到按钮字段并将其隐藏(未经测试,但我认为可行......)
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;
}
}
}