你需要指定在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>