Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 467
Inderpal Singh Avatar asked Oct 25 '25 06:10

Inderpal Singh


1 Answers

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
    }
}
like image 162
Tim Schmelter Avatar answered Oct 26 '25 18:10

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!