开发者

How to add a ComboBox to an asp.net unbound GridView

I wonder how I can add a ComboBox column to an unbound GridView through cod开发者_StackOverflowe at runtime.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜