您如何約束您的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
事件。
您有使用模板字段的原因嗎?對比說一個ButtonField
?如果您使用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字段 - 是的,我不明白爲什麼你不能還是用ButtonField字段處理。這裏有一個片斷找到在綁定行數據的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;
}
}
}
使用ButtonField字段,有沒有辦法以編程方式隱藏或顯示呢?我可能會或很多不顯示按鈕,取決於當前迭代中的某個值。我讀過的所有內容都說我必須切換到TemplateField中的標準按鈕。 用我目前的方法,我使用RowDataBound事件來檢查當前的迭代,找到按鈕,並可能隱藏它。 – Deane 2010-02-02 19:11:42
我認爲這一定是可能的。用附加的示例代碼編輯我的答案。 – 2010-02-02 19:23:26