Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

Add checkbox to programmatically generated GridView

<Columns>
  <asp:TemplateField>
    <itemtemplate>
      <asp:CheckBox ID="CheckBoxRowItem" runat="server" />
    </itemtemplate>
  </asp:TemplateField>
</Columns>

How do I do this programmatically in the C# code behind?

This checkbox will NOT be databound.


My current method:

private void BuildGridView(DataView dv)
      {            
            this.GridViewSearchResults.Columns.Clear();
            this.GridViewSearchResults.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

/////////////////DOES NOT SEEM TO WORK:
            //CheckBoxField cbf = new CheckBoxField();
            //this.GridViewSearchResults.Columns.Add(cbf);

            foreach (DataColumn dc in dv.Table.Columns)
            {
                  
                  BoundField bf = new BoundField();
                  bf.HeaderText = dc.ColumnName;
                  bf.DataField = dc.ColumnName;
                  bf.HeaderStyle.ForeColor = System.Drawing.Color.White;
                  bf.HeaderStyle.BackColor = System.Drawing.Color.Black;
                  bf.SortExpression = dc.ColumnName;
                  
                  this.GridViewSearchResults.Columns.Add(bf);
            }
      
            this.GridViewSearchResults.AutoGenerateColumns = false;
            this.GridViewSearchResults.DataSource = dv;            
            this.GridViewSearchResults.DataBind();            
      }

Avatar of OptimusSupernova
OptimusSupernova
Flag of Canada image

Instead of adding a BoundField, you could add a CheckBoxField in your foreach.
Avatar of Tom Knowlton

ASKER

Please provide code.

Remember I want the checkbox to be in the far left column, and it will be unbound.
ASKER CERTIFIED SOLUTION
Avatar of OptimusSupernova
OptimusSupernova
Flag of Canada image

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
Will a CheckBoxField still work if it is unbound?
Yes you don't need to bind it.
It is not showing up.

the other fields show up, but not the checkbox.