Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Make a TemplateField with Checkbox Through Code-behind?

How can I add a template field with a checkbox to my DetailsView object through C# code-behind? I'm having trouble figuring it out from reading the asp.net code.

I already have the TemplateField and CheckBox object instantiated with values assigned to the properties. But when I use Fields.Add() the checkbox doesn't show-up.

    TemplateField tf_ForMalls = new TemplateField();
    tf_ForMalls.HeaderText = "For Malls";

    CheckBox chk_ForMalls = new CheckBox();
    chk_ForMalls.ID = "chkDelete";

    tf_ForMalls.ItemTemplate = chk_ForMalls as ITemplate;

    dv_SpotDetail.Fields.Add(tf_ForMalls);
like image 598
Erick Garcia Avatar asked Apr 26 '11 04:04

Erick Garcia


People also ask

How to convert BoundField to TemplateField?

To convert an existing BoundField into a TemplateField, click on the Edit Columns link from the GridView's smart tag, bringing up the Fields dialog box. Select the BoundField to convert from the list in the lower left corner and then click the "Convert this field into a TemplateField" link in the bottom right corner.

How to use CheckBox in GridView?

From the GridView s smart tag, click on the Edit Templates link and then drag a CheckBox Web control from the Toolbox into the ItemTemplate . Set this CheckBox s ID property to ProductSelector . With the TemplateField and CheckBox Web control added, each row now includes a checkbox.

How to add TemplateField in GridView in ASP net?

how to add templatefield or Column dynamically in gridview in asp.net c# when auto generated column property is false. Add column with text box value in grid view on button click event .

What is ItemTemplate?

The ItemTemplate template is required by the ListView control. It usually contains controls to display the field values of a record. If you want to let users modify the data, you also usually add buttons to the ItemTemplate template that let the user select a record, switch to edit mode, or delete a record.


1 Answers

You will need a custom class derived from ITemplate to get this working

public class MyTemplate : ITemplate
{
    #region ITemplate Members

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

    #endregion
}

Then in the code

TemplateField tf = new TemplateField();
tf.ItemTemplate = new MyTemplate();
detvw.Fields.Add(tf);

You can have the constructor to pass in the parameters for 'control id' or specifying the ListItemType

Hope this helps

like image 117
V4Vendetta Avatar answered Sep 28 '22 02:09

V4Vendetta