Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys,
I Have Test.aspx and CommonGrid.ascx
ASP.NET
Test.aspx
<uc:CommonGrid runat="server" .../>

C#
Test.aspx.cs
protected void Page_LoadComplete(object sender, EventArgs e)
{
   //DataBind to gridview
}

CommonGrid.ascx
<asp:GridView ID="CommonGrid" runat="server"></asp:GridView>
<asp:Button ID="Test" runat="server" Text="TestClick"/>

C#
CommonGrid.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
   //Dynamically add column to grid view
}


C#
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   //do other configuration changing cell bgcolor based on cell value etc.
}


C#
protected void Test_Click(object sender, EventArgs e)
{
   //identify checkbox marked as checked. FYI checkbox is one of the control dynamically created inside gridview.
}


Problem
When I click on the Test button it perform postback and then the GridView will be recreated from Page_Load handler and Test_Click will be executed (of CommonGrid.ascx). When i tried to find the checkboxes control inside Test_Click event i can't seem to find it.

Question
How can i make sure that the checkbox is already created and holding the client updated value right after Click event postback?

Solution sharing my solution just incase other pipz also encountered this issue, most of the article i found only discusses dynamically created gridview with in the page and not in usercontrol.
Default.aspx
ASP.NET
<uc:GridView ID="TestGridView"  runat="server"/>


Default.aspx.cs this is the tricks, you execute databinding right after the creation of the column. this actually is the fix, and may not mind the rest of the code.
C#
protected void Page_Init(object sender, EventArgs e)
    {
        this.TestGridView.Load += this.MyDataBindHandler;
    }

    protected void MyDataBindHandler(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("MyName");

        DataRow dr = table.NewRow();
        dr["MyName"] = "aa";
        table.Rows.Add(dr);

        dr = table.NewRow();
        dr["MyName"] = "bb";
        table.Rows.Add(dr);

        this.TestGridView.BindData(table);
    }


WebUserControl.ascx
ASP.NET
<asp:Button ID="Button1" runat="server" Text="ClickMe" OnClick="Button1_Click"/>
<asp:GridView ID="CommonGridView" runat="server"></asp:GridView>


WebUserControl.ascx.cs
C#
protected void Page_Load(object sender, EventArgs e)
    {
        this.ConfigureGridColumn();
    }

    private void ConfigureGridColumn()
    {
        this.CommonGridView.Columns.Clear();

        //add ordinary column
        BoundField bf = new BoundField();
        bf.DataField = "MyName";
        bf.HeaderText = "Name";

        //add checkbox
        TemplateField tf = new TemplateField();
        tf.ItemTemplate = new CreateCheckBox("chkMyCheckBox");
        tf.HeaderStyle.Wrap = false;
        this.CommonGridView.Columns.Add(tf);

        this.CommonGridView.Columns.Add(bf);
    }

    public void BindData(DataTable dt)
    {
        this.CommonGridView.DataSource = dt;
        this.CommonGridView.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < this.CommonGridView.Rows.Count; i++)
        {
            CheckBox chk = this.CommonGridView.Rows[i].FindControl("chkMyCheckBox") as CheckBox;
            Response.Write(string.Format("Chk: {0}, ", chk.Checked.ToString()));
        }
    }


Template class for checkbox
C#
public class CreateCheckBox : ITemplate
{
    string checkboxID;
    public CreateCheckBox(string id)
    {

        this.checkboxID = id;

    }
    public void InstantiateIn(Control container)
    {
        CheckBox chk = new CheckBox();
        chk.ID = checkboxID;

        container.Controls.Add(chk);
    }
}
Posted
Updated 15-Feb-12 15:17pm
v4
Comments
Jephunneh Malazarte 15-Feb-12 5:17am    
thanks for editing digimanus :)

Test.aspx
ASP.NET
<%@ Register Src="~/WebUserControl.ascx" TagName="GridView" TagPrefix="uc" %>
<uc:GridView ID="TestGridView"  runat="server"/>


Test.aspx.cs
1. Replaced Page_LoadComplete with Page_LoadCompleted or any other names. Buttom line is that the databinding must not be inside LoadComplete event.
C#
e.g: protected void MyDataBindHandler(object sender, EventArgs e)
{
// do databindings to gridview
}


2. Create a Page_Init handler and attach the MyDataBindHandler to the usercontrol load event. this is to make sure that the binding happens right after adding of columns in gridview.
C#
e.g: protected void Page_Init(object sender, EventArgs e)
{
    this.TestGridView.Load += this.MyDataBindHandler;
}


WebUserControl.ascx
ASP.NET
<asp:Button ID="Button1" runat="server" Text="ClickMe" OnClick="Button1_Click"/>
<asp:GridView ID="CommonGridView" runat="server"></asp:GridView>



WebUserControl.ascx.cs
1. In Page_Load handler call the method to add the columns in the gridview
C#
e.g: protected void Page_Load(object sender, EventArgs e)
{
    this.ConfigureGridColumn();
}


2. Get handle the click event


Sequence is that
* One first load
Default8.aspx Page_Init -> WebUserControl.ascx Page_Load -> Default8.aspx MyDataBindHandler

* On Button click
Default8.aspx Page_Init -> WebUserControl.ascx Page_Load -> Default8.aspx MyDataBindHandler -> Button1_Click

thanks to Vivek Thakuri got this info:
If you create a dynamic control in the Page_Load event, and add it to a PlaceHolder or Panel (with view state turned on), then this dynamic control will maintain its state even though it was not created in the Page_Init().

i have updated the question and added a solution section with codes. note that the code is dirty just to address the issue but can be improved.
 
Share this answer
 
v6
use in Test_Click method:
C#
CheckBox box = (CheckBox)sender;
GridViewRow row = (GridViewRow)box.NamingContainer;


Now you have the row that was clicked in and all controls should be available.
 
Share this answer
 
Comments
Jephunneh Malazarte 15-Feb-12 5:19am    
you mean to say attached the Test_Click event handler of the checkbox inside the gridview?
Herman<T>.Instance 15-Feb-12 7:57am    
yes
After reloading the page all gridview is getting created again that's why you are not able to find the value.. This is your exact problem correct?

If yes then inside Page_Load method whatever codes you have written just put
it inside !IsPostBach.. Like:

C#
protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           //Your code goes here...
       }
   }


Accept the answer if you like it..

All the best... :)
 
Share this answer
 
Comments
Jephunneh Malazarte 15-Feb-12 5:12am    
hello AmitKumar89 thanks for your quick response :).
I can't place it inside !IsPostBack because if i do that the GridView will not be recreated unless I did not dynamically create my gridview.
Jephunneh Malazarte 15-Feb-12 5:15am    
Sorry I didn't answer your question.
Actually my problem is that i can't get the updated value of the dynamically created control.

if your control is dynamically created you need to recreate it upon postback. And to remember the value is to use viewstate however i can't seem to make it work.. huhuhuhu...
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           //Dynamically add column to grid view

        }
    }
protected void Test_Click(object sender, EventArgs e)
{
 
for(index=0;index< MyGridView.rows.count;index++)
{
//find your check box using the index

}
 

}
 
Share this answer
 
Comments
Jephunneh Malazarte 15-Feb-12 5:29am    
i can't add filter ispostback otherwise my gridview will become empty after postback because i am dynamically creating it.
once control is dynamically created, we need to recreate it after postback and use viewstate to restore the value.

but my problem is i can't restore the value.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900