Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Im trying to add a checkbox to a gridview dynamically. I have added a checkbox statically called selectCheckbox, but i clear all columns in another function and need to re-add another checkbox if it equals null. Thanks in advance!

protected void mainGridView_RowCreated(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow &&
           (e.Row.RowState == DataControlRowState.Normal ||
            e.Row.RowState == DataControlRowState.Alternate))
        {
            CheckBox selectCheckbox = (CheckBox)e.Row.Cells[1].FindControl("selectCheckbox");

            if (selectCheckbox == null)
            {
                selectCheckbox = new CheckBox;  //this is where i need to add a checkbox to the gridview!!!              
            }
           
        }
    }
Posted

You can use RowDataBound event for that below code sample for your reference
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
       {
           if (e.Row.RowType == DataControlRowType.DataRow &&
             (e.Row.RowState == DataControlRowState.Normal ||
              e.Row.RowState == DataControlRowState.Alternate))
           {

               if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
               {
                   CheckBox selectCheckbox = new CheckBox();
                   //Give id to check box whatever you like to
                   selectCheckbox.ID = "newSelectCheckbox";
                   e.Row.Cells[1].Controls.Add(selectCheckbox);

               }
           }
       }
 
Share this answer
 
try this code...

C#
void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{

  if(e.Row.RowType == DataControlRowType.DataRow)
  {
    CheckBox cbx = new CheckBox();    
    // bind checkbox control with gridview :
    e.Row.Cells[0].Controls.Add(cbx);
  }
}


be sure about the position of the check box.
 
Share this answer
 

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