Sandeep Kumar

Sandeep Kumar

  • 1.1k
  • 683
  • 59.1k

Dynamically created LinkButton's Click event is not firing in RowComma

Feb 22 2022 7:38 AM

Dynamically created LinkButton's Click event is not firing in RowCommand of GridView.

protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int J = e.Row.RowIndex + 1;
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            ImageButton imgbtn = new ImageButton();
            Label lbl = new Label();
            HiddenField hdnRemarks = new HiddenField();
            if (i == (dt.Columns.Count - 1) && J > 2)
            {
                imgbtn.ID = "imgbtn" + i; 
                imgbtn.CommandName = "viewremarks"; 
                imgbtn.Command += LinkButton_Command;
                e.Row.Cells[i].Controls.Add(imgbtn);
                imgbtn.Height = 15;
                imgbtn.Width = 15;
                imgbtn.ImageUrl = "~/App_Themes/Images/magnifier-1.png";

                hdnRemarks.ID = "hdnRemarks" + i;
                e.Row.Cells[i].Controls.Add(hdnRemarks);
                hdnRemarks.Value = dt.Rows[J - 1][dt.Columns[i].ColumnName.ToString()].ToString();
            }
            else
            {
                lbl.ID = "lbl" + i;
                e.Row.Cells[i].Controls.Add(lbl);
                lbl.Text = dt.Rows[J - 1][dt.Columns[i].ColumnName.ToString()].ToString();
            }
        }
    }
}

protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "viewremarks")
   {
       //GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
   }
}

protected void grdResult_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int J = e.Row.RowIndex + 1;
        for (int i = 1; i < e.Row.Cells.Count; i++)
        {
            ImageButton imgbtn = new ImageButton();
            Label lbl = new Label();
            HiddenField hdnRemarks = new HiddenField();
            if (i == e.Row.Cells.Count && i > 2)
            {
                imgbtn.ID = "imgbtn" + i;
                imgbtn.CommandName = "viewremarks"; 
                imgbtn.Command += LinkButton_Command;
                e.Row.Cells[i].Controls.Add(imgbtn);
                imgbtn.Height = 15;
                imgbtn.Width = 15;
                imgbtn.ImageUrl = "~/App_Themes/Images/magnifier-1.png";

                hdnRemarks.ID = "hdnRemarks" + i;
                e.Row.Cells[i].Controls.Add(hdnRemarks);
            }
            else
            { 
                lbl.ID = "lbl" + i;
                e.Row.Cells[i].Controls.Add(lbl);
                lbl.Text = Convert.ToString(J);
            }
        }
    }
}