i have a gridview which has a checkbox column. The header is of this column is a checkbox.
When it is checked all the values get checked and vice-verse.
I do this using javascript.
The problem is if i check it and perform any other event on the page which requires a postback the checked values disappear. I dont want them to disappear.
here is my code:
<script type="text/javascript">
function checkAllBoxes() {
//get total number of rows in the gridview and do whatever
//you want with it..just grabbing it just cause
var totalChkBoxes = parseInt('<%= GridView1.Rows.Count %>');
var gvControl = document.getElementById('<%= GridView1.ClientID %>');
//this is the checkbox in the item template...this has to be the same name as the ID of it
var gvChkBoxControl = "Select_CheckBox";
//this is the checkbox in the header template
var mainChkBox = document.getElementById("chkBoxAll");
//get an array of input types in the gridview
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Select_CheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<!-- The rest of your rows here -->
</Columns>
</asp:GridView>
Thanks for the help.
Make your checkbox a server-side control that uses the view state by adding runat="server". It will then maintain its value across post backs.
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/>
And change your JavaScript to select the id that ends in chkBoxAll. I use jQuery in the example below:
//this is the checkbox in the header template
var mainChkBox = $('input[id$="chkBoxAll"]');
However, if you sort your gridview rows or use paging, you will likely come across less friendly behavior.
Related
I would like to return text label in my gridview with Jquery
<div class="risksContainer">
<div class="risksGrid">
<asp:GridView ID="GridViewRisks" runat="server"
[...]
/>
<Columns>
<asp:TemplateField HeaderText="...">
<ItemTemplate>
<div class="CodeProductColumn">
<asp:Label ID="IDRisk" runat="server" CssClass="IDRiskIndex" Text="<%# Item.ID_Risk %>" />
<asp:Repeater ID="LabelRepeatCodeProduct" runat="server"
[....]
</asp:Repeater>
</div>
</ItemTemplate>
I try many solutions, but i don't know how i get the label Text of my selected row.
javascript :
function blabla(){
var Id_risk = $(".risksContainer .risksGrid .IDRiskIndex").text();
alert("Id_risk =" + Id_risk );
return Id_risk ;
}
(this function start when i click on edit button in my row)
I get text of all rows in my gridview and not only my selected row.
I try with "parent, child, first, selected, rows[]...
I am beginner and i'm desperate to find it
Use try in JavaScript:
<script type="text/javascript">
function blabla()
{
// find gridview
var gv = document.getElementById("<%=GridViewRisks.ID %>");
// get row count
var gvRowCount = gv.rows.length;
var i = 1;
for (i; i<= gvRowCount - 1; i++)
{
// get label value from column 2
alert(gv.rows[i].cells[2].childNodes[1].innerHTML);
}
return false;
}
</script>
<asp:Button ID="Button1" runat="server" OnClientClick=" blabla();return false;" ... />
Assuming you set the selected row in code behind with GridViewRisks.SelectedIndex = i, you can set the CSS class of the selected row.
<asp:GridView ID="GridViewRisks" runat="server" SelectedRowStyle-CssClass="selectedRow">
Now you can use that class to get the correct row in jQuery.
var Id_risk = $(".selectedRow .IDRiskIndex").text();
I have two check boxes with the GridView TemplateField. I want to uncheck the checked boxes after submission. My gridview
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" DataKeyNames="ShiftID"
Width="177px" onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChbGrid" runat="server"
oncheckedchanged="ChbGrid_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChbGridHead" runat="server" AutoPostBack="True"
Font-Bold="True" oncheckedchanged="ChbGridHead_CheckedChanged" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I tried in below mentioned methode
public void checkboxclear()
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if(chkrow.Checked==true)
{
chkrow.Checked = false;//it works
}
else
{
CheckBox chkrow1 = (CheckBox)row.FindControl("ChbGridHead");
if (chkrow1.Checked == true)
{
chkrow1.Checked = false;//it shows error like "Object reference not set to instance of an object"
}
}
}
How can I improve my code to solve this issue? Why I am unable to call these check boxes inside the aspx.cs page
You need to check for the RowType becuase your second checkbox is in the HeaderTemplate. For that gridview generates special HeaderRow. That you can directly access and set the value to it.
public void checkboxclear()
{
foreach (GridViewRow row in GridView1.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if(chkrow.Checked)
chkrow.Checked = false;
}
}
CheckBox chkrow1 = (CheckBox)GridView1.HeaderRow.FindControl("ChbGridHead");
if (chkrow1.Checked)
chkrow1.Checked = false;
}
Also you don't need to use the chkrow.Checked==true. chkrow.Checked it returns boolean value so that direactly should check in if condition.
I guess I don't know when you are calling this function, but the correct place to pre-set values is in the row databound event.
Having said that the reason your code is blowing up is that you are looking for the header check box in every row, and it is only in the header row. Just access the header through the gridviews header property and do your find control there.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.headerrow(v=vs.110).aspx
Something like
CheckBox chkHeader = (CheckBox)Gridview1.HeaderRow.FindControl("ChbGridHead");
I am having header in gridview that labels as "xls" and a checkbox, that when selected should select all the checkbox columns in gridview and unchecking the xls column should uncheck all the columns.
I am following two links:
Link-1
Here, the totalChkBoxes variable is coming null (despite my gridview has rows). In fact when debugging the JS, code inside parseInt and below line is coming as ''
Link-2
Here also the GridView2 variable is coming null.
One common change that i am doing in both the JS is replacing the <%=.....%> by <%#....%>
Please guide as to what i am doing wrong. You can also help by giving some suitable link to implement the desired functionality
CODE UPDATED WITH MY WORKING JS
<script type="text/javascript" language="javascript">
function checkAllBoxes() {
var gvControl = document.getElementById("gvSample");
//this is the checkbox in the item template.
var gvChkBoxControl = "chkSelectItem";
//Header Template checkbox.
var mainChkBox = document.getElementById("chkBoxAll");
//Array of Inputs in gridview.
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
GRIDVIEW CODE
<asp:TemplateField>
<HeaderTemplate>
<table style="width: 15px" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblXls" runat="server" Text="xls"></asp:Label>
<br />
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelectItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Thanks!
Try changing your parseInt to something like this to see if it helps at all. I know it's only a small change, but small things tend to break JS code:
var totalChkBoxes = parseInt("<%=gvTest.Rows.Count%>");
Secondly, if you have runat="server" on the checkbox in the header, you may need to change this line if your JSFunction:
var mainChkBox = document.getElementById("<%=chkBoxAll.UniqueID%>");
I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box").
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
I found the answer. and its working...
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
and girdview code is...
<asp:BoundField ItemStyle-Width ="100px" DataField ="EventStartDate" DataFormatString ="{0:g}" HeaderText ="<%$ Resources:stringsRes, ctl_EventList_StartDate %>" SortExpression ="EventStartDate" HtmlEncode ="true" ItemStyle-Wrap ="false" />
<asp:BoundField ItemStyle-Width="100px" DataField="EventDate" DataFormatString="{0:g}" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Date %>" SortExpression="EventDate" HtmlEncode="true" ItemStyle-Wrap="false" />
<asp:ButtonField ItemStyle-Width="150px" ButtonType="Link" DataTextField="EventName" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Event %>" SortExpression="EventName" CommandName="show_details" CausesValidation="false" />
<asp:BoundField DataField="EventLocation" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Location %>" SortExpression="EventLocation" />
<asp:TemplateField HeaderText ="Select">
<ItemTemplate >
<asp:CheckBox ID="chkDownloadSelectedEvent" runat ="server" AutoPostBack ="false" Onclick="eachCheck();"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
and there is a link button ....
I havnt used the checkbox in grid view but would you not do a for loop around the columns in gridview and check the state? Myabe add a count and if 0 then alert.
var grid = document.getElementById("gridId"); //Retrieve the grid
var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
var isValid = false;
for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
isValid = true;
break;
}
}
}
if(!isValid) {
alert('Check at least one checkbox');
}