Tuesday, May 7, 2013

Generate Select All Checkbox control in C# , ASP.Net

Hi guys, today I faced a scenario where I need to create (auto generate) a Select All CheckBox control by C# code behind at runtime and and insert it to the Ajax Control toolkit TabPanel.

Once user will check the Select All checkbox all the other checkbox within that Tab will get checked without post back of page. For opposing post back and achieving mark as check JavaScript is the best option coming in mind. And hence I choose the same.

I wrote JavaScript Global function which accept Select All CheckBox Control Id and look for the related controls and auto generate the required Id for them.

Generate Select All Checkbox : 2bexpert

For achieving this functionality I have written Below mention code:

C# Code for Generating CheckBox Dynamically (Auto Generate Checkbox):

#region Generate SelectAllCbx

    private void GenerateSelectAllCbx(string cbxId, int index, int width, bool isChecked, AjaxControlToolkit.TabPanel tab)

    {

        CheckBox cbAll = new CheckBox();

        cbAll.Attributes.Add("Value", "All");

        cbAll.ID = cbxId + index.ToString();

        cbAll.Text = "Select All";

        cbAll.Width = Unit.Pixel(width);

        cbAll.Checked = isChecked;

        cbAll.Enabled = !isChecked;

        cbAll.Attributes.Add("onclick", "javascript: SelectAll(this," + index.ToString() + ");");

        tab.Controls.Add(cbAll);

 

    }

    #endregion

Just we need to call this method where we want to insert Select All CheckBox:

GenerateSelectAllCbx("cbEngRating_", 4, 750, false, tabICFRating);

 

Whenever this Method would get called it will Insert a Checkbox (Select All) and handle other automatically for achieving that below is JavaScript Code:

function SelectAll(control_id, x) {

        var chkAll = $(control_id);

        var autoId = control_id.id.substring(0, control_id.id.length - x.toString().length)

        for (var i = 0; i < x; i++) {

            $("#" + autoId + i).attr("Checked", chkAll.prop("checked"));

        }

            }

Here I am passing the Control Id and the Postfix Id to generate auto ID.

That’s it now you are able to select auto generated multiple checkbox and mark them check.




Cheers…

Anand Tiwari….