Link to home
Start Free TrialLog in
Avatar of csetzkorn
csetzkorn

asked on

creating a TemplateField in a GridView dynamically

Hi,

Usually, I am adding a TemplateField to a gridview like this:

<asp:TemplateField>
<itemTemplate>
        <input class="btn" onclick="window.location = 'bla.aspx?bla_uid=<%# DataBinder.Eval(Container.DataItem, "bla_uid") %>'; return false;" name="more_details" id="more_details" type="submit" value="More Details" />
</itemTemplate>
</asp:TemplateField>

I would like to do the same dynamically from the code behind file.

I know how to add a boundfield:

bound_field = new BoundField();
bound_field.HeaderText = "Title";
bound_field.DataField = "title";
bound_field.SortExpression = "title";

grid_view.Columns.Add(bound_field);

However, I havent found anything on TemplateFields. Any ideas?

Many thanks in advance.

BW,

Chris
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium 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
Avatar of csetzkorn
csetzkorn

ASKER

Thanks, I was actually toying with a ITemplate implementation but did not get to work. However, the example you have provided me with give me enough info to get it to work:

public class PageItemTemplate : System.Web.UI.ITemplate
{
    System.Web.UI.WebControls.ListItemType templateType;
    private string columnName;

    // ####################################################################

    public PageItemTemplate(System.Web.UI.WebControls.ListItemType type, string columnName)
      {
            this.templateType = type;
        this.columnName = columnName;
      }

    // ####################################################################

    public void InstantiateIn(System.Web.UI.Control container)
    {
        Label l = new Label();
        l.DataBinding += new EventHandler(this.l_DataBinding);
        container.Controls.Add(l);

    }

    // ####################################################################

    private void l_DataBinding(Object sender, EventArgs e)
    {
        // get the control that raised this event
        Label l = (Label) sender;
        // get the containing row
        GridViewRow row = (GridViewRow) l.NamingContainer;
        // get the raw data value and make it pretty
        string RawValue = DataBinder.Eval(row.DataItem, columnName).ToString();

        Button b = new Button();
        b.OnClientClick = @"window.location = 'page_details.aspx?page_uid=" + RawValue + "'; return false;";
        b.Text = "More Details";
        b.CssClass = "btn";
        l.Controls.Add(b);

    }

    // ####################################################################
}