Search code examples
c#asp.netgridviewcheckboxoncheckedchanged

Checked_Change Event of programatically generated Checkbox inside GridView Row


I have a GridView which holds user data. When the Page_Load Method is called, I get data using a DataTable and then bind it to the GridView. At the end of each row, I have added a CheckBox. This CB is used as a pointer for which entity the user wants to edit.

My problem is the Check_Changed Event of the CheckBoxes. I do not know how to add a handler if the control is generated programmatically. I also need the index of the row (a field value is also possible, but the column header and the column itself are hidden).

 foreach (GridViewRow gvr in grdMitgliedsliste.Rows)
 {
       //add checkbox for every row
       TableCell cell = new TableCell();
       CheckBox box = new CheckBox();
       cell.Controls.Add(box);
       gvr.Cells.Add(cell);

       //Hide columns for userid, status, etc. 
       gvr.Cells[0].Visible = false;
       gvr.Cells[3].Visible = false;
       gvr.Cells[4].Visible = false;
       gvr.Cells[5].Visible = false;
       gvr.Cells[8].Visible = false;
       gvr.Cells[9].Visible = false;  
 } 

I have already tried implementing the handler from here, but it gives me no index argument so the program cannot determine in which row the checkbox was checked.


Solution

  •    protected void Page_Load(object sender, EventArgs e)
            {
                List<string> names = new List<string>();
                names.Add("Jhonatas");
    
                this.GridView1.DataSource = names;
                this.GridView1.DataBind();
    
                foreach (GridViewRow gvr in GridView1.Rows)
                {
                    //add checkbox for every row
                    TableCell cell = new TableCell();
                    CheckBox box = new CheckBox();
                    box.AutoPostBack = true;
                    box.ID = gvr.Cells[0].Text;
    
                    box.CheckedChanged += new EventHandler(box_CheckedChanged);
                    cell.Controls.Add(box);
                    gvr.Cells.Add(cell);
                }
            }
    
            void box_CheckedChanged(object sender, EventArgs e)
            {
                string test = "ok";
            }