Link to home
Start Free TrialLog in
Avatar of Dixon8402
Dixon8402

asked on

Programmatically adding template field in ASP.NET GridView problem

I am trying to programmatically add a template field to an ASP.NET GridView control using C# code behind. I can successfully add the template field with not problem, the problem I am having is capturing events of the template.
For instance, Before adding the columns dynamically I had a column that was a template field that contained a check box.  When clicked the checkbox called some javascript that highlighted the selected row. Is their a way of still being able to do this using the dynamic method.? Any help would be greatly appreciated.
Thanks
//  Here is where I am adding the template field
protected void buildColumns(string searchType)
{
     GridViewMaterial.Columns.Clear();
 
     // Email Field
     TemplateField templateEmail = new TemplateField();
     templateEmail.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "test");
     templateEmail.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "test");
     GridViewMaterial.Columns.Add(templateEmail);
}
 
// Here is the code for building the template field
public class GridViewTemplate : ITemplate
{
     private DataControlRowType templateType;
     private string columnName;
 
     public GridViewTemplate(DataControlRowType type, string colname)
     {
          templateType = type;
          columnName = colname;
     }
 
     public void InstantiateIn(System.Web.UI.Control container)
     {
          switch (templateType)
          {
              case DataControlRowType.Header:
                  CheckBox checkAll = new CheckBox();
                  checkAll.Text = "Select All";
                  checkAll.Attributes.Add("selectAll", "onclick='checkAll(this.form);'");
                  container.Controls.Add(checkAll);
                  break;
              case DataControlRowType.DataRow:
                  CheckBox cb = new CheckBox();
                  cb.ID = "emailCheckBox";
                  cb.Text = "";
                  cb.Attributes.Add("selectRow", "onclick='colorRow(this);'");
                  container.Controls.Add(cb);
                  break;
              default:
                  break;
          }
      }
}
 
// I am basically just looking for a way to capture the click of the checkbox

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of vs1784
vs1784

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dixon8402
Dixon8402

ASKER

Your solution worked but it also led me to figure out the problem with what I was trying and why it wasn't working.

cb.Attributes.Add("selectRow", "onclick='colorRow(this);'");
needed to be changed to
cb.Attributes.Add("selectRow", "colorRow(this);");
then all is good.
Thank you for your help.
dafg