tags:

views:

89

answers:

1

I wonder how I can add a ComboBox column to an unbound GridView through code at runtime.

A: 

Programmatically:

I've used the following class (but for DropDown and CheckBox binding) in the past which implements ITemplate.

public class AddTemplateToGridView : ITemplate
{
    String columnName;

    public AddTemplateToGridView(String colname)
    {
        columnName = colname;
    }

    void ITemplate.InstantiateIn(System.Web.UI.Control container)
    {
        if (columnName == "yourField")
        {
            ComboBox cb = new ComboBox();
            cb.DataBinding += new EventHandler(cb_DataBinding);
            container.Controls.Add(cb);
        }
    }

    void cb_DataBinding(object sender, EventArgs e)
    {
        ComboBox cb = (ComboBox)sender;
        GridViewRow container = (GridViewRow)cb.NamingContainer; 
        Object dataValue = DataBinder.Eval(container.DataItem, columnName); 
        if (dataValue != DBNull.Value) 
        {
            // Assign ComboBox vals if necessary
            ... = dataValue
        }
    }
}

Use by declaring your GridView and TemplateField in the codebehind:

GridView newGrid = new GridView();
TemplateField field = new TemplateField();
field.HeaderText = "columnName";
field.ItemTemplate = // some item template
field.EditItemTemplate = new AddTemplateToGridView("yourField");
newGrid.Columns.Add(field);

or Declaratively:

<asp:GridView ID="GridView1" runat="server">  
<Columns>              
    <asp:TemplateField HeaderText="yourField">
        <ItemTemplate>
            <asp:Label runat="server" Text ='<%# Eval("yourField") %>' />
        </ItemTemplate>
        <EditItemTemplate>         
            <%--Your ComboBox--%>
        </EditItemTemplate>  
    </asp:TemplateField>
</Columns>
</asp:GridView>

Hope this helps.

Brissles
I can't get this to work. InstantiateIn is never called for my EditItemTemplate. For ItemTemplate it works, however...?
danbystrom
Turned out I had to recreate the grd in the RowUpdating event. Then it worked.
danbystrom