tags:

views:

166

answers:

2

Hi

I have a datagrid with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..

Here is my code:

public class ItemTemplate : ITemplate
{
    //Instantiates the checkbox
    void ITemplate.InstantiateIn(Control container)
    {
        CheckBox box = new CheckBox();            
        box.CheckedChanged += new EventHandler(this.OnCheckChanged);
        box.AutoPostBack = true;
        box.EnableViewState = true;
        box.Text = text;
        box.ID = id;
        container.Controls.Add(box);
    }

    public event EventHandler CheckedChanged;

    private void OnCheckChanged(object sender, EventArgs e)
    {
        if (CheckedChanged != null)
        {
            CheckedChanged(sender, e);
        }
    }
}

and Here is the event

private void OnCheckChanged(object sender, EventArgs e)
{

}

Thanks In advance

+2  A: 

Typically we've used the "CommandName" property on the control. This will pass through to the RowCommand event of the GridView. You can then inspect the value of CommandName and act accordingly.

Adam Fyles
A: 

since you add the control dynamically, you also need to add it to the viewState (see overrides for LoadViewState and SaveViewState).

when you do postback, the page has no information about the checkbox you've added and that's why you don't get any event.

please check this article: http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-%5F2800%5FPart-1%5F2900%5F.aspx

it describes those issues very well.

Greg