Generally we add the checkbox to the header of the Gridview in a template field when AutoGenerateColumns value is false.
But sometimes we need to add checkbox to the header of the column even when AutoGenerateColumns value is true. For example if we are binding the data table which is dynamically generated to the gridview and we need to add checkboxes for all the columns in the gridview.
We can use gridview PreRender event to add checkbox to the all columns of the gridview as shown below.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
protected void BindData()
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employees.xml"));
gv1.DataSource = ds.Tables[0];
gv1.DataBind();
}
catch (Exception ex)
{
}
}
protected void gv1_PreRender(object sender, EventArgs e)
{
for (int i = 0; i < gv1.HeaderRow.Cells.Count; i++)
{
CheckBox chk = new CheckBox();
chk.ID = gv1.HeaderRow.Cells[i].Text;
chk.Text = gv1.HeaderRow.Cells[i].Text;
gv1.HeaderRow.Cells[i].Controls.Add(chk);
}
}
}
As shown above, create object for Checkbox class and add this object to the each cell Controls of the gridview header.