GridView with SelectAll CheckBox using JavaScript and XMLGridView with SelectAll CheckBox using JavaScript and XML
Introduction
In this article i am explaining how to bind GridView by a xml file and a common function that we need in gridview i.e. a check box that select all the check box of every row in grid without postback using JavaScript.
Using Code
Using the following code you can easily bind a GridView with a XML file and provide check box select all functionality.
We will cover this article in the following sections:
1. Getting data from XML file and Binding Gridview with data.
2. Design GridView with SelectAll CheckBox in HeaderRow.
3. JavaScript function to Select and Unselect All CheckBoxes.
Now let's get started with step 1.
1. Getting data from XML file and Binding Gridview with data
I have used a Default.aspx page to show a grid on that page. When the page is load, following code get data from XML file and bind the grid. Additionally it also store number of rows in viewstate for select all function.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataSet dsCatalog = new DataSet();
dsCatalog.ReadXml(Server.MapPath("~/App_Data/CDCatalog.xml"));
gvCdCatalog.DataSource = dsCatalog.Tables[0];
gvCdCatalog.DataBind();
ViewState["RowCount"] = dsCatalog.Tables[0].Rows.Count;
}
}
2. Design GridView with SelectAll CheckBox in HeaderRow
Now we design GridView to show data and make a template field to show a selectall checkbox in header and checkbox in all rows and call the JavaScript function fnSelectAll(); onclick event of selectall checkbox.
3. JavaScript function to Select and Unselect All CheckBoxes
Here we write JavaScript function to Select and Unselect All CheckBoxes. It gets number of rows in grid from viewstate and check whether selectall checkbox is checked or not and according to that it select checkbox or unselect checkbox.
In the above function, I used 'gvCdCatalog_ctl01_chkSelectAll’ it is genrated at runtime by the browser. You can see it by right click on webpage and select view source.
So in your case, you have to change the id according to your gridview id and chekbox id like here ‘gvCdCatalog’ is GridViewId and ‘chkSelectAll’ is checkbox id. Then we check that this check box is checked or not. If it is checked then start a for loop and it get each check box and assign true to it’s checked property.
I also write a JavaScript function ‘fnUnSelect()’ unselect the selectAll CheckBox if any of checkbox is unselect.