Saturday, September 15, 2007

Synchronize checkboxes in a GridVIew

Imagine this scenario, you have a GridView where it contains various columns as checkboxes and u want to impose a constraint that restrict the user from selecting a specific checkbox while the others are selected. ( by Unchecking the other checked checkboxes)

The following function takes as parameters GridView ID and CheckBox ID ( the one that when clicked uncheck the other checkboxes in a specific row in the gridview).

 

 

private void SynchCheckBoxes(string gridName, string checkboxName)
    {
        GridView grid = (GridView)this.Page.FindControl(gridName);
        if (grid == null)
        {
            foreach (Control ctl in Page.Controls)
            {
                if (ctl.HasControls())
                {
                    grid = (GridView)ctl.FindControl(gridName);
                }
            }
        }
        for (int y = 0; y < grid.Rows.Count; y++)
        {
            StringBuilder s = new StringBuilder();
            CheckBox c3 = new CheckBox();
            ArrayList t = new ArrayList();
            int index = (int)grid.DataKeys[y].Value;
            c3 = (CheckBox)grid.Rows[y].FindControl(checkboxName);

            foreach (Control ctrl in grid.Rows[y].Controls)
            {
                if (ctrl.HasControls())
                {
                    foreach (Control ctrls in ctrl.Controls)
                    {

                        if (ctrls.GetType() == typeof(CheckBox) && ctrls.ID != checkboxName)
                        {
                            t.Add(ctrls);
                        }

                    }
                }

            }
            for (int i = 0; i < t.Count; i++)
            {
                CheckBox c = (CheckBox)t[i];

                c.Attributes.Add("onclick", "document.getElementById('" + c3.ClientID + "').checked = false;");

                s.Append("document.getElementById('" + c.ClientID + "').checked = false;");

            }
            c3.Attributes.Add("onclick", s.ToString());

        }
    }

 

Have fun optimizing it!

No comments: