简体   繁体   中英

ASP.NET gridview dynamically added columns issue

I've got simple gridview below, where columns are generated dynamically on page load when not post back.

<asp:GridView runat="server" ID="gridMain"
 CssClass="table table-striped table-bordered"
 OnRowCommand="gridMain_onRowCommand"
 OnRowDataBound="gridMain_onRowDataBound"
 OnRowEditing="gridMain_onRowEditing"
 OnRowUpdating="gridMain_onRowUpdating"
 OnRowCancelingEdit="gridMain_onRowCancelingEdit"
 AutoGenerateColumns="False"
 DataKeyNames="StudentId">
</asp:GridView>

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var actionField = new TemplateField
            {
              HeaderText = "Action",
              ItemTemplate = new BtnEditTemplate(),
              EditItemTemplate = new BtnUpdateTemplate()
            };
            gridMain.Columns.Add(nameField);
        }
     }

Here is BtnEditTemplate()

public class BtnEditTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
        var btnEdit = new LinkButton {ID = "btnEdit" CommandName = "Delete"};
        container.Controls.Add(btnEdit);
    }
}

The problem is that gridMain_onRowCommand event is not firing in this case. The only one event that works is page load. Can anyone help me?

You have your code in the following method. Did you create this one?

protected void gridMain_onRowCommand(object sender, GridViewCommandEventArgs e)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM