是否有任何方法可以在gridview取消编辑事件中找到控制隐藏字段。 我已经尝试了一些方法,但是没有用
protected void InnerGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
InnerGrid.EditIndex = -1;
HiddenField hdCaID = InnerGrid.Rows[e.RowIndex].FindControl("hdCaID") as HiddenField;
}
这是我的代码,但我找不到隐藏字段,我得到null异常错误。感谢任何帮助..
答案 0 :(得分: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>