你怎么绑定你的GridView
?您是否使用数据源控件?如果您在 期间手动绑定Page_Load
,则由于网格每次往返都绑定,因此事件处理程序可能无法正确捕获。如果是这种情况,您可能想尝试以下方法:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
您可以发布示例绑定代码以与您的标记一起使用吗?
如果你真的想强制解决这个问题,你可以挂钩到 Grid 上的 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
事件。
您使用“模板”字段是否有原因?VS说一个ButtonField
?如果您使用 a ButtonField
,那么您可以挂钩RowCommand
事件。
标记片段:
<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 上的问题 - 是的,我不明白为什么您仍然无法处理按钮字段。这是在行数据绑定期间查找按钮字段并将其隐藏的片段(未经测试,但我认为可以工作......)
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;
}
}
}