I have a gridView which is movable with dragAndDrop. But i am able only for move the row of gridView using dragAndDrop. This is my code:
gridView1.datasource = dt;
gridView1.dataBind();
<asp:GridView ID="GridView3" CellPadding="5" CellSpacing="0"
OnRowDataBound="GridView3_RowDataBound"
ForeColor="#333" runat="server"
AutoGenerateColumns="true">
</asp:GridView>
<asp:Button ID="Save" runat="server" Text="Save" onclick="btnsave_Click" />
// use of JQuery for dragAndDrop
$(function () {
$("[id*=GridView1]").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'pointer',
axis: 'y',
dropOnEmpty: false,
start: function (e, ui) {
ui.item.addClass("selected");
},
stop: function (e, ui) {
ui.item.removeClass("selected");
},
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
});
Using this code, i am only able to move rows of gridView. But i want, when i will click on save button then the order of rows which are changed by dragAndDrop will be shown. thanks.
Related
In my page when it's creating, everything is working fine but when I am clicking on the button to show the selected row, then my grid view is not rendering as a datatable. What I need to do to fix this or what I am doing wrong?
My script:
<script type="text/javascript">
$(function () {
$('[id*=gvTest]').prepend($("<thead></thead>").append($(this).find("tr:first"))).DataTable({
"responsive": true,
"sPaginationType": "full_numbers",
});
});
$(document).ready(function () {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnRead').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
});
} );
</script>
My Grid:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" >
</asp:BoundField>
<asp:BoundField DataField="PatientName" HeaderText="PatientName" >
</asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" >
</asp:BoundField>
<asp:BoundField HeaderText="Sex" DataField="Sex" >
</asp:BoundField>
<asp:BoundField HeaderText="Mod" DataField="Modality" >
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
When my page is created:
Everything is working fine, but when I click a button then this happens:
What do I need to do now to fix this problem ?
The UpdatePanel refreshes the DOM, so any changes made to it with jQuery are lost. You need to call DataTable() again after an Async PostBack. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
createDataTable();
});
createDataTable();
function createDataTable() {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
}
</script>
The best way to fix this issue is by implementing this in pageLoad function.
In this case I used a Gridview:
function pageLoad() {
$("<thead></thead>").append($("#grvPast tr:first")).prependTo($("#grvPast"));
$('#grvPast').dataTable();
}
after using a lots of others code i did'nt get a proper solution so i used this on my page load and its working fine
gvTest.UseAccessibleHeader = true;
//adds <thead> and <tbody> elements
gvTest.HeaderRow.TableSection =
TableRowSection.TableHeader;
I have gridview showing columns BusRoute,BusNo and Action.Where action contains the linkbuttons to display another gridview.I want to display it in jquery dialog.My codes are.
ASPX Code:
First Gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClientClick="showDialog();">Shipment Status</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
Second Gridview:
<div class="gridview_stop" id="popup">
<asp:GridView ID="Stops" runat="server" AutoGenerateColumns="False" CellPadding="6" Width="190px">
<Columns>
<asp:BoundField HeaderText="Bus Stop" DataField="StopName" HeaderStyle-BackColor="#006B89">
<HeaderStyle BackColor="#006B89" Font-Size="18px" Font-Bold="false"></HeaderStyle>
<ItemStyle BackColor="#E0E0E0" HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
Code Behind File:
protected void search_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("spGetRoutes", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BusStop1", Source.Text);
cmd.Parameters.AddWithValue("#BusStop2", Destination.Text);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
adapter.Dispose();
cmd.Dispose();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Route.DataSource = ds.Tables[0];
Route.DataBind();
Stops.DataSource = null;
Stops.DataBind();
Lblmsg.Text = "";
}
else
Lblmsg.Text = "No Direct Bus Between These Stop";
Lblmsg.ForeColor = Color.WhiteSmoke;
Route.Dispose();
Route.DataBind();
Stops.Dispose();
Stops.DataBind();
}
protected void Route_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string Name = Route.SelectedRow.Cells[0].Text;
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
string connetionString = "Data Source=.;Initial Catalog=BusService;uid=sa;Password=Murli#925";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand cmd = new SqlCommand("spGetStops", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
int BusNo= Convert.ToInt32(Name);
cmd.Parameters.AddWithValue("#BusNo",BusNo);
adapter1.SelectCommand = cmd;
adapter1.Fill(ds1);
adapter1.Dispose();
cmd.Dispose();
connection.Close();
Stops.DataSource = ds1.Tables[0];
Stops.DataBind();
}
Jquery Function:
<script type="text/javascript">
$("#lnkbtn").live("click",
function showDialog() {
$("#popup").dialog({
show: { effect: "fold", duration: 4000 },
hide: { effect: "fold", duration: 4000 },
});
return false;
});
$(document).click(function (event) {
if (!$(event.target).closest('#popup').length) {
if ($('#popup').is(":visible")) {
$('#popup').dialog('close');
}
}
})
</script>
Thanks & Regards.
Take a look at your rendered html when you run the page. Unless you set ClientIDMode to Static I doubt that your button ID's are $("#lnkbtn") but more like $("#gvWhatever_lnkbtn_0")
Set OnClientClick="showDialog();" or $("#lnkbtn").live("click", function showDialog(){...}) no need to do both.
Using a Server Control button to activate a popup usually doesn't work. Especially if GridView Row Selection is enabled. I can't tell if your first GridView has that feature enabled as I only see a portion of the listing. But what tends to happen is you trigger a postback while trying to display the popup so you never see the popup.
Also your second popup contains a gridview, which requires a databind. so you need to make sure the gridview is populated with the data before activating the popup
Two methods for showing a popup using jquery from within a Gridview:
A portion of a GridView markup with 2 TemplateField's
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div>
<div class="rs-icon rs-icon-info tooltip-marker" role="button">
</div>
<div id="ContactInfo" style="display:none;">
<table id="tblContactDetail" class="ContactDetail Note">
<tr>
<td style="width: 80px">Name</td>
<td style="width: 100%">
<asp:Literal ID="Literal1" runat="server"
Text='<%# Eval("expert_name") %>' />
</td>
</tr>
.
.
.
</table>
</div>
</div>
<ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CV">
<ItemTemplate>
<div id="divButtonViewCV" runat="server"
class="rs-icon rs-icon-cv" role="button"
onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>' >
</div>
</ItemTemplate>
</asp:TemplateField>
In the above markup I'm setting up for two styles of "popup". The first Template uses jQueryUI ToolTip widget which is activated on mouseover/out. This is nice because it doesn't require a click which means no worries about a postback mucking up the works. The interesting thing here is that I'm using a div as button.
How it works: The div with the .tooptip-marker class is set up to activate a jqueryui tooltip which will display the contents of <div id="ContentInfo"> by grabbing the inner html of the sibling div of the activating button. Note that this div is styled as display:none; so that the content is available for the tooltip but hidden so the main GridView displays as normal.
For brevity, I included only a portion of the content of <div id="ContentInfo">. But It can contain anything really. In my code it's a simple <table> containing contact information fields (using bound <asp:Literal> controls) that are part of the primary GridView data source.
But this could just have easily been an embedded GridView with it's own data source that is bound in the OnRowDatabound event of the primary GridView.
The following jquery sets up the widget. See jQueryUI ToolTip widget for more complete documentation
$( function() {
$( document ).tooltip( {
items: ".tooltip-marker",
content: function() {
return $( this ).next().html();
},
position: {
my: "left top",
at: "right+5 top-5"
}
} )
} );
The second Template field is used to activate a popup. This is where you have to be careful about postbacks. Again I use a <div> styled as an icon and treated as a simple button because I've added onclick.
Clicking this button displays a popup so you can view a persons CV in PDF format. The PDF is stored in our database as a varbinary. Here I use another jquery addon, (colorbox), to display the PDF as a popup over the page.
In the ViewPDF() function below note that we prevent the "bubbling up" of the click event to the GridView by setting cancelBubble = true (for older IE) or a call to stopPropagation() (all other browsers).
In this code, colorbox sets up an iframe and passes the href parameter to its src attribute. I'm making a call to an .ashx page which is an asp Generic Handler which allows us to serve up other type of content without standard web page overhead. This could just as easily been configured to accept a standalone .aspx page where you could maybe place your secondary grid.
// This plain object is used by the call to colorbox(), please
// refer to colorbox documentation for details.
var colorboxDataExpertCV = {
height: "85%",
width: 900,
opacity: .30,
fixed: true,
iframe: true,
returnFocus: false,
href: ''
}
// ========================================================
// In the Template above, the onclick code:
// onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>'
//
// Renders to:
// onclick="ViewPDF(12345)"
//
// PdfHandlerExpertsCV.ashx is an GenericHandler that retrieves
// the CV from our database and writes the byte array to the
// colorbox iframe as an "application/pdf" content type which
// triggers native browser pdf management either by internal
// viewer or installed PDF plugin
// ========================================================
function ViewPDF( p ) {
if ( event.stopPropagation )
event.stopPropagation();
else
event.cancelBubble = true;
if ( p && p > 0 ) {
colorboxDataExpertCV.href = "/PdfHandlerExpertsCV.ashx?cvid=" + p;
$.colorbox( colorboxDataExpertCV );
}
return false;
}
Addendum
Let me make it more clear, I need to bind the data in 2nd Gridview and
display this Gridview2 in Jquery dialog .This data will be binded and
displayed in dialog from on the click event of linkbutton inside
Gridview1
As I said above, you cannot bind a GridView (server side event) and then popup a jquery ui dialog (client side event) without introducing much more complexity. You have to make sure all the data you need for the popup is available by the time you're ready to hit the button that opens the dialog.
The simplest way to accomplish this is to embed GridView2 within GridView1 and take care of the binding all at once. It's not pretty or efficient and, depending on the number of items shown in each, can slow down the page. But if you have only a few lines for each it should be acceptable.
Embed GridView2 and DataSource2 in the <ItemTemplate> of a <TemplateField> of GridView1.
Bind GridView2 in the RowDataBound event of Gridview1 using an appropriate row field or datakey field from GridView1 and then calling GridView2.DataBind().
Add a element to the same TemplateField
Refer to the jquery dialog modal form example which shows how to trigger a dialog from a button click. In your case substitute the second GridView for the Form in the example.
IMPORTANT be mindful that gridview row item id's get "mangled" so you should not use id's in the jquery calls but use jquery selectors that are based on element name plus class markers, ie: $("button.marker") for a button defined like this: <button class="marker">.
Addendum: 2015-Jun-24
CSS (<head> tag)
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui.css" />
<script type="text/javascript" src="Scripts/jquery-2.1.4.min.js"> </script>
<script type="text/javascript" src="Scripts/jquery-ui-1.11.4.min.js"> </script>
<style>
.btn_styling {
text-align: center;
width: 32px;
margin: 2px;
cursor: pointer;
border: 1px solid gray;
border-radius: 3px;
/* add a background image to the div
to make the div look like a button */
/* background-image: url('...') */
}
.ui-dialog-titlebar-close {
display: none;
}
</style>
HTML (.aspx)
<form id="form1" runat="server">
<div style="width: 400px;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="user_id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an <img> element...anything really">X</div>
<div style="display: none;">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />
<asp:BoundField DataField="add_edit_date" HeaderText="Date Added" SortExpression="add_edit_date" DataFormatString='{0:dd-MMMM, yyyy}'/>
<asp:BoundField DataField="add_edit_by" HeaderText="Added By" SortExpression="add_edit_by" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT email, add_edit_date, add_edit_by FROM tbl_users WHERE (user_id = #user_id)">
<SelectParameters>
<asp:Parameter Name="user_id" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT top 10 user_id, user_name from tbl_users">
</asp:SqlDataSource>
</div>
<div id="dialogContainer">
</div>
</form>
Code Behind (VB):
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv2 As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
Dim sds As SqlDataSource = DirectCast(e.Row.FindControl("SqlDataSource2"), SqlDataSource)
sds.SelectParameters("user_id").DefaultValue = GridView1.DataKeys(e.Row.RowIndex).Value
gv2.DataBind()
End If
End Sub
jQuery to implement Dialog:
<script type="text/javascript">
var dialogOptions = {
autoOpen: false,
appendTo: "#dialogContainer",
modal: true,
height: "auto",
width: "auto",
title: "Dialog Title",
closeOnEscape: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
};
$( function() {
$( ".dialog-marker" ).on( "click", function() {
var d = $( this ).next( "div" ).first().dialog( dialogOptions );
d.dialog( "open" );
} );
} );
</script>
I am working on an asp.net application and I have a delete image button like this:
<asp:GridView ID="grdPaymethods" runat="server" ShowHeader="False" GridLines="None" AutoGenerateColumns="False" OnRowDataBound="grdPaymethods_RowDataBound" OnRowDeleting="grdPaymethods_RowDeleting">
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<Columns>
<asp:ImageButton ID="IBtnDelete" runat="server" ToolTip="Click to delete"
CommandArgument='<%# Eval("MethodId") %>'
OnClientClick="javascript:return deleteItem(this.name, this.alt);"
ImageUrl="~/Images/Delete.png" AlternateText='<%# Eval("MethodId") %>'
CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
and I see that row deleting event is fired. but I want to use linkbutton instead of image button. So I used this code:
<asp:LinkButton ID="IBtnDelete1" runat="server" ToolTip="Click to delete"
CommandArgument='<%# Eval("MethodId") %>'
OnClientClick="javascript:return deleteItem(this.name, this.alt);"
Text="Delete" AlternateText='<%# Eval("MethodId") %>'
CommandName="Delete"></asp:LinkButton>
It shows link button, but clicking link button just refreshes page and doesnt call row deleting event. I tried OnRowCommand="grdPaymethods_RowCommand" event and linkbutton on click events as well but they are not fired and page just refreshed.
here are js functions:
function deleteItem(uniqueID, itemID) {
e.preventDefault();
var dialogTitle = 'Permanently Delete Item ' + itemID + '?';
$("#deleteConfirmationDialog").html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please click delete to confirm deletion.</p>');
$("#deleteConfirmationDialog").dialog({
title: dialogTitle,
buttons: {
"Delete": function () {
__doPostBack(uniqueID, '');
$(this).dialog("close");
},
"Cancel": function () { $(this).dialog("close"); }
}
});
$('#deleteConfirmationDialog').dialog('open');
return false;
}
$(function () {
InitializeDeleteConfirmation();
});
function InitializeDeleteConfirmation() {
$('#deleteConfirmationDialog').dialog({
autoOpen: false,
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
and row deleting event:
protected void grdPaymethods_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// cancel the automatic delete action
e.Cancel = true;
// do the delete
// _categoryResposite.DeleteCategories(Convert.ToInt32(e.id));
grdPaymethods.DataSource = customer.PaymentMethods.OrderByDescending(a => a.Preferred);
grdPaymethods.DataBind();
}
Please suggest solution to it.
I am using a jQuery multiselect dropdown in ASP.NET I need to get all the selected values, but I am getting only the last selected value from the dropdownlist on the server side after postback.
Script:
<script type="text/javascript">
$(document).ready(function () {
$('.department).multiselect({
show: ["bounce", 5], hide: ["blind", 1],
close: function () {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function (index, item) {
values.push($(item).val());
});
$("input[id*=selectedValues]").val(values.join(","));
document.getElementById("<%=hdnDepartment.ClientID %>").value = values;
}
})
.multiselectfilter();
});
</script>
<asp:HiddenField ID="hdnDepartment" runat="server"></asp:HiddenField>
<asp:HiddenField ID="hdnEmployee" runat="server" />
<asp:DropDownList ID="ddlDepartment" runat="server" Width="150px" CssClass="department" onselectedindexchanged="ddlDepartment_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
Try joining the values and then writing it to a hidden field..
$('[id*=hdnDepartment]").val(values.join()) ;
//OR
document.getElementById("<%=hdnDepartment.ClientID %>").value = values.join();
Also looks like you are losing the vent once the postback occurs. So you need to reattach it once the postback is done .. Try this.
<script type="text/javascript">
$(document).ready(function () {
PostBack();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(PostBack);
});
function PostBack(){
$('.department).multiselect({
show: ["bounce", 5], hide: ["blind", 1],
close: function () {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function (index, item) {
values.push($(item).val());
});
$("input[id*=selectedValues]").val(values.join(","));
document.getElementById("<%=hdnDepartment.ClientID %>").value = values;
}
})
.multiselectfilter();
}
</script>
I have a GridView in ASP.NET/C# with a CheckBoxField, a BoundField and 2 ButtonFields. All 4 of them has a header to make clear where the column stands for. At the Page_Load event I set the ВataЫource of the GridView to my filled DataTable.
I want to make it easier to use for the user, and want to make a checkbox in the header. When that checkbox is checked by the user, all CheckBoxes should be checked in the GridView. I have set the HeaderText of the CheckBoxField to <input type='checkbox' />, and it shows a checkbox in the header now.
Now I want to add a function to that checkbox, that when it's checked, all CheckBoxes will be checked en vice versa. I tried to do it with jQuery, but it didn't work because I can't find a way to give all the CheckBoxes in the GridView the same ID or NAME.
Is there a event that occurs when I check the HTML based checkbox within the header? If yes, which event?
If no, how can i trigger a event when I check that checkbox, and change the GridView from my code-behind.
And if none of that is possible, how can i do it on another way, with javascript, jQuery or maybe with a ASP.net control.
I hope you can help me with this, but please don't expect i'm a code guru. I'm a intern at a company where the need a system, with this functionality.
Update:
Thank you everyone for helping me out. What is the easiest way to get the DataSource back into the DataTable, because i need to know which rows were selected and which were not?
Using jQuery, you get all the check boxes inside the GridView, and then for each one you change the status as you like. You call this javascript function from onclick of a link or a button, or what ever you like.
function CheckAll()
{
var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');
updateButtons.each( function() {
// use this line to change the status if check to uncheck and vice versa
// or make it as you like with similar function
jQuery(this).attr("checked", !this.checked);
});
}
try this code according to you
in grid view
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="headerchkbox" runat="server" CssClass="chkheader" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxAssign" runat="server" CssClass="chkitems" />
</ItemTemplate>
</asp:TemplateField>
java script
<script type="text/javascript">
$(window).bind('load', function () {
var headerChk = $(".chkheader input");
var itemChk = $(".chkitems input");
headerChk.bind("click", function () { itemChk.each(function () { this.checked = headerChk[0].checked; })
});
itemChk.bind("click", function () { if ($(this).checked == false) headerChk[0].checked = false; });
});
</script>
Here is a sample I have put together for you.
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstObjects = new List<string> { "aaa", "bbb" };
GridView1.DataSource = lstObjects;
GridView1.DataBind();
}
}
If you are using the latest version of jQuery (1.7)
Use the following:
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).click(function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).click(ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>