findcontrol does not find dynamically created cont

2019-08-03 16:45发布

问题:

I implemten ITemplate to dynamically create a Template field

TemplateField isReqField = new TemplateField();
isReqField.HeaderText = "Lizenz anfordern";
isReqField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, DataControlRowState.Normal, "isRequested", "bool");
isReqField.EditItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, DataControlRowState.Edit, "isRequested", "bool");

gvLicence.Columns.Add(isReqField);

I implement InstantiateIn

        public void InstantiateIn(System.Web.UI.Control container)
        {

... 

                            CheckBox ckRequest = new CheckBox();
                            ckRequest.ID = "ckRequest";
                            ckRequest.DataBinding += new EventHandler(this.CkIsRequested_DataBinding);
                            container.Controls.Add(ckRequest);

...

        }

with the DataBinding Handler

private void CkIsRequested_DataBinding(Object sender, EventArgs e)
{

    CheckBox ckRequest = (CheckBox)sender;
    GridViewRow row = (GridViewRow)ckRequest.NamingContainer;
    ckRequest.Checked = (bool)DataBinder.Eval(row.DataItem, columnName);
}

But then in the RowUpdating Handler I cannot find my checkBox Control with the FindControl Method:

protected void gvLicence_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    CheckBox chb = (CheckBox)gvLicence.Rows[e.RowIndex].FindControl("ckRequest");
    bool requestValue = chb.Checked;

It throws an Exeption because gvLicence.Rows[e.RowIndex].FindControl("ckRequest") is null.

Many thanks for your attention and help.