2016-08-24 91 views
0

是否有任何方法可以在gridview取消編輯事件內找到控件hiddenfield。 我已經嘗試了一些methodes,但不工作FindControl Inside Gridview取消編輯事件

protected void InnerGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 
{ 
    InnerGrid.EditIndex = -1; 
    HiddenField hdCaID = InnerGrid.Rows[e.RowIndex].FindControl("hdCaID") as HiddenField; 
} 

這是我的代碼,但我不能找到hiddenfield我得到空例外error.Any幫助表示讚賞..

回答

0

你需要指定在Cell在那裏你試圖找到隱藏字段:

int i = e.RowIndex; 
HiddenField hdCaID = InnerGrid.Rows[i].Cells[1].FindControl("hdCaID") as HiddenField; 

這是一個完整的例子,後面的代碼:

public partial class GridViewCancel : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if(!Page.IsPostBack) 
     { 
      BindData(); 
     } 
    } 

    public void BindData() 
    { 
     var c1 = new Customer { HiddenID = 11, FirstName = "Name1", LastName = "Surname1" }; 
     var c2 = new Customer { HiddenID = 22, FirstName = "Name2", LastName = "Surname2" }; 
     var c3 = new Customer { HiddenID = 33, FirstName = "Name3", LastName = "Surname3" }; 

     InnerGrid.DataSource = new List<Customer> { c1, c2, c3 }; 
     InnerGrid.DataBind(); 
    } 

    protected void InnerGrid_RowEditing(object sender, GridViewEditEventArgs e) 
    { 
     InnerGrid.EditIndex = e.NewEditIndex; 
     BindData(); 
    } 

    protected void InnerGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 
    { 
     int i = e.RowIndex; 
     HiddenField hdCaID = InnerGrid.Rows[i].Cells[1].FindControl("hdCaID") as HiddenField; 
     if (hdCaID != null) 
     { 
      string value = hdCaID.Value; 
     } 

     InnerGrid.EditIndex = -1; 
     BindData(); 
    } 
} 

.ASPX:

<asp:GridView ID="InnerGrid" runat="server" AutoGenerateEditButton="True" AutoGenerateColumns="false" OnRowCancelingEdit="InnerGrid_RowCancelingEdit" OnRowEditing="InnerGrid_RowEditing"> 
    <Columns> 
     <asp:TemplateField> 
      <ItemTemplate> 
       <asp:HiddenField ID="hdCaID" runat="server" Value='<%# Eval("HiddenID") %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:BoundField DataField="FirstName" /> 
     <asp:BoundField DataField="LastName" /> 
    </Columns> 
</asp:GridView> 
相關問題