Dynamically add TemplateField Columns to GridView in ASP.NET

ASP.NET

aspx

Add OnRowCreated event

C#


    protected void Page_Load(object sender, EventArgs e)
    {
        if(!this.IsPostBack)
        {
            TemplateField tfield = new TemplateField();
            tfield.HeaderText = "Country";
            //set width
            tfield.HeaderStyle.Width = Unit.Pixel(100);
            //set text align
            tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView1.Columns.Add(tfield);
        }
    }


    protected void gvList_RowCreated(object sender, EventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
            for(int a = 0; a < e.Row.Controls.Count ; a++)
            {
                Button button = new Button();
                button.Style["color"] = "Green";
                button.Text = "⚠";
                button.ID = "gvbtn" + a;
                button.Visible = false;
                button.CommandName = "certificationInfo";
                button.Attributes.Add("CssClass", "");
                button.Attributes.Add("onMouseOver", "this.className='MouseSetting2'");
                button.Attributes.Add("onMouseOut", "");
                button.Style["background-color"] = "transparent";
                button.Style["border-color"] = "transparent";
                button.Style["Width"] = "20px";
                button.Style["padding"] = "0px";
                e.Row.Cells[a].Controls.Add(button);
            }
        }
    }