Inderpal Singh
Inderpal Singh

Reputation: 270

cannot find checkbox control added on rowdatabound grid view even

I have added control by

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";


        DataRowView dr = (DataRowView)e.Row.DataItem;
        chk.Checked = (dr[0].ToString() == "true");


        e.Row.Cells[1].Controls.Add(chk);
        e.Row.TableSection = TableRowSection.TableBody;
    }

and trying to find by

     if (GridView2.Rows.Count>0)
    {
        foreach (GridViewRow row in GridView2.Rows)
        {
            CheckBox cb =(CheckBox) GridView2.Rows[2].Cells[1].FindControl("chkb");
            if (cb != null && cb.Checked)
            {
                Response.Write("yest");
            }

        }
    }

But i cannot find it ... Actually my problem is that i need to create a dynamic list.. for that i am using gridview

Upvotes: 4

Views: 11140

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

You need to create dynamic controls on every postback since it is disposed at the end of the current life-cycle. But RowDataBound is just triggered when you databind the GridView what is done typically only if(!IsPostBack) (at the first time the page loads).

You should create dynamic controls in RowCreated instead which is called on every postback. You can databind these controls then in RowDataBound if you want, since RowCreated is triggered first.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";
        e.Row.Cells[1].Controls.Add(chk);
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var chk = (CheckBox)e.Row.FindControl("chkb");
        // databind it here according to the DataSource in e.Row.DataItem
    }
}

Upvotes: 3

Related Questions