i am using the following code to get datakey value when row double click, now i want to use this key value in serverside, how can i get this value there(or) how to pass this value to server side?
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function RadGrid1_RowDblClick(sender, args) {
var keyValue = dataItem.getDataKeyValue('WageID');
// want to get this keyvalue in server side
}
</script>
</telerik:RadScriptBlock>
<telerik:RadGrid ID="RadGrid1" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView ClientDataKeyNames="ID">
</MasterTableView>
<ClientSettings>
<ClientEvents OnRowDblClick="RadGrid1_RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Finally i got the answer for this question, following is the answer
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function RadGrid1_RowDblClick(sender, args) {
//changed code here
var grid = $find("<%= RadGrid1.ClientID %>");
var MasterTable = grid.get_masterTableView();
var row = MasterTable.get_dataItems()[eventArgs.get_itemIndexHierarchical()];
var key = MasterTable.getCellByColumnUniqueName(row, "WageID"); // get the value by uniquecolumnname
var ID = key.innerHTML;
MasterTable.fireCommand("MyClick2",ID);
}
</script>
</telerik:RadScriptBlock>
<telerik:RadGrid ID="RadGrid1" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView ClientDataKeyNames="ID">
</MasterTableView>
<ClientSettings>
<ClientEvents OnRowDblClick="RadGrid1_RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
//add this code under itemcommand event of radgrid.
if (e.CommandName == "MyClick2")
{
object obj = e.CommandArgument;
string ID = obj.ToString();
//logic to fulfill our requirment.
}
Here might solve your problem
http://demos.telerik.com/aspnet-ajax/grid/examples/overview/defaultcs.aspx
You can get the datakeyvalue on client side using the following code:
function OnRowDblClick(sender, args) {
var key= args.getDataKeyValue("WageID");
document.getElementById('<%= HidenField1.ClientID %>').value = key;
}
To pass these value to server side one suggestion is you can assign this to a hiddenfield and access that hiddenfield in server side.
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 the following code which suppoesedly disables or enables a textbox depending on the value in a drop down list.
Now this is how I am making a reference to this code from the drop down lists:
Unfortunately, the code is generating an exception. I believe that I am using the wrong event handler, that is, OnSelectedIndexChanged. How can I remedy the situation please?
1) replace OnSelectedIndexChanged with onchange
and
2) replace
var DropDown_Total = document.getElementById("DropDown_Total")
with
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
for all getElementById
3) replace (DropDown_Date.options[DropDown_Date.selectedIndex].value
with
(DropDown_Date.options[DropDown_Date.selectedIndex].text for both dropdown
try this it's working
<script type="text/javascript">
function DisableEnable() {
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
var Textbox_Total = document.getElementById("<%= Textbox_Total.ClientID %>")
var DropDown_Date = document.getElementById("<%= DropDown_Date.ClientID %>")
var Textbox_Date = document.getElementById("<%= Textbox_Date.ClientID %>")
if (DropDown_Total.options[DropDown_Total.selectedIndex].text == "Any Amount") {
Textbox_Total.disabled = true;
}
else {
Textbox_Total.disabled = false;
}
if (DropDown_Date.options[DropDown_Date.selectedIndex].text == "Any Date") {
Textbox_Date.disabled = true;
}
else {
Textbox_Date.disabled = false;
}
}
</script>
html
<asp:TextBox runat="server" ID="Textbox_Total" />
<asp:TextBox runat="server" ID="Textbox_Date" />
<asp:DropDownList ID="DropDown_Total" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Amount</asp:ListItem>
<asp:ListItem>Exact Amount</asp:ListItem>
<asp:ListItem>Below Amount</asp:ListItem>
<asp:ListItem>Above Amount</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDown_Date" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Date</asp:ListItem>
<asp:ListItem>Exact Date</asp:ListItem>
<asp:ListItem>Before</asp:ListItem>
<asp:ListItem>After</asp:ListItem>
</asp:DropDownList>
Use onchange event which will work for javascript function calling. OnSelectedIndexChanged is server side event.
just replace OnSelectedIndexChanged with onchange because onchange is handled by js. OnSelectedIndexChanged is handled by code behind.
Tutorial: how to disable/enable textbox using DropDownList in Javascript
In this function we pass dropdownlist id and textbox id as parameter in js function
<script type="text/javascript">
function DisableEnableTxtbox(DropDown, txtbox) {
if (DropDown.options[DropDown.selectedIndex].text == "free") {
txtbox.disabled = true;
}
else {
txtbox.disabled = false;
}
}
</script>
Now add the following code:
<td align="center" class="line">
<asp:DropDownList ID="ddl_MonP1" runat="server" CssClass="ppup2" onchange="DisableEnableTxtbox(this,txt_MonP1);"></asp:DropDownList>
<asp:TextBox ID="txt_MonP1" runat="server" CssClass="ppup" placeholder="Subject"></asp:TextBox>
</td>
I've a gridview in which there is an add and remove row facility.I want to knoow how could i remove a particular gridview row when corresponding remove button is clicked.
I've searched everywhere but nothing find quite useful to me
Heres my code
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="gdlbtnRemove" runat="server"
OnClientClick="RemoveRow(this)">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
This is my javascript code
<script type="text/javascript">
function RemoveRow(rowindex,objref)
{
var row=objref.parentNode.parentNode;
row.Remove();
}
</script>
Im new to javascript........
Try this:
apsx:
<ItemTemplate>
<asp:LinkButton ID="gdlbtnRemove" runat="server"
OnClientClick="return RemoveRow(this)">Remove</asp:LinkButton>
</ItemTemplate>
Javascript:
function RemoveRow(item) {
var table = document.getElementById('myGridView');
table.deleteRow(item.parentNode.parentNode.rowIndex);
return false;
}
Old post i know but Tsachi's Answer was almost perfect for me except
This
var table = document.getElementById('GridviewID');
had to become this
var table = document.getElementById("<%= GridviewID.ClientID %>");
In case anyone else looks at this
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>
I want to get the value of check box placed inside grid view. if check box is checked, it textbox in that row should be enable and if it is again uncheked, the textbox should get clear and disabled. I asked this question few hours back but still didn't get satisfactory answer.
I tried like this.
//My grid code.
<asp:GridView ID="DeptGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="DeptId" HeaderText="ID"/>
<asp:BoundField DataField="DeptName" HeaderText="Department"/>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="addToCompanyBox" onClick="EnableHODBox()" runat="server" />
</ItemTemplate>
<HeaderTemplate>
Add
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hodNameBox" runat="server" Width="200px" Enabled="false"></asp:TextBox>
</ItemTemplate>
<HeaderTemplate>
Dept Head
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//My javascript code
<script type="text/javascript">
function EnableHODBox() {
//alert('hello');
var GridView = document.getElementById('<%=DeptGrid.ClientID %>');
//var GridView = document.getElementById('');
var DeptId;
if (GridView.rows.length > 0) {
for (Row = 1; Row < GridView.rows.length; Row++) {
// DeptId = GridView.rows.cell[0];
if (GridView.rows[Row].cell[3].type == "checkbox")
// var chkbox = GridView.rows[Row].cell[3].type == "checkbox"
(GridView.rows[Row].cell[3].type).checked = true;
}
}
}
</script>
This solution is tested and works using only JavaScript (no jQuery is required for this solution!).
1. C# Part (In Page_Load Method)
In Page_Load we need to add a small hack:
foreach(GridViewRow row in YourGridViewControlID.Rows)
{
if (row.RowType == DataControlRowType.DataRow )
{
((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");");
}
}
This way, we are adding the JavaScript function call on the OnChange event of every CheckBox of our GridView. What is special and we can't achieve through the HTML is that we are passing the Row Index of each one in the JavaScript function, something that we need later.
2. Some important notes for the HTML Part
Make sure that both Checkbox control and Textbox control but more importantly your GridView Control has static id by using the ClientIDMode="Static" as shown bellow:
<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />
And for the GridView control:
<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">
3. Javascript Part
And then in your JavaScript file/code:
function TextboxAutoEnableAndDisable(Row) {
// Get current "active" row of the GridView.
var GridView = document.getElementById('YourGridViewControlID');
var currentGridViewRow = GridView.rows[Row + 1];
// Get the two controls of our interest.
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
// If the clicked checkbox is unchecked.
if( rowCheckbox.checked === false) {
// Empty textbox and make it disabled
rowTextBox.value = "";
rowTextBox.disabled = true;
return;
}
// To be here means the row checkbox is checked, therefore make it enabled.
rowTextBox.disabled = false;
}
4. Some Notes for the above implementation
Note that in the JavaScript code, at the line:
var currentGridViewRow = GridView.rows[Row + 1];
the [Row + 1] is important to make this work and should not change.
And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
The .cells[2] and .cells[0] is maybe different for you, so you have to choose the correct number in the [].
Usually, this will be the column number of your GridView starting counting from 0.
So if your CheckBox was in the first column of the GridView then you need .cells[0].
If your TextBox is in the second column of your GridView then you need .cells[1] (in my case above, TextBox was in the third column of my GridView and therefore, I used .cells[2])
You can use the onclick JavaScript instead of the OncheckedChanged event which is a CheckBox server side event.
<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />
Edit:
var GridView = document.getElementById('<%=DeptGrid.ClientID %>')
Edit: Upon your request in comment
if (GridView.rows[Row].cell[2].type == "checkbox")
{
if (GridView.rows[Row].cell[2].childNodes[0].checked)
{
GridView.rows[Row].cell[3].childNodes[0].disabled=false;// Enable your control here
}
}
I also found that the statement if (GridView.rows[Row].cell[2].type == "checkbox") results in an error, GridView.rows[Row].cell[2].type is undefined. The code I have running now is as follows:
var grid = document.getElementById('<%=grdResults.ClientID%>');
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
if (grid.rows[row].cells[0].childNodes[0].checked) {
// do something here
alert('function for row ' + row);
}
}
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);
}
Hi here you are having very easy Solution
Suppose your grid is like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="64px"
Width="389px" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="EmployeeId">
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF66FF" ForeColor="#660033" />
</asp:GridView>
and your javascript to find controls inside your grid is
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnAddToGrid").click(function () {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
var employeeId = $row.find("span[id*='lblEmployeeId']").text();
var firstname = $row.find("span[id*='lblFirstName']").text();
var lastname = $row.find("span[id*='lblLastName']").text();
alert("ID :" + employeeId +"\n" + "Name :" + firstname +" "+ lastname );
});
});
</script>
Find controls inside the grid using java script:
for (var r = 1; r < grid.rows.length; ++r) {
var indexValue = 0; //based on browser. //IE8
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
if (typeof (txtPeriod.value) == "undefined")//IE9
indexValue = 1
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
alert(txtPeriod.value);
}
var x = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
var i;
var cnt = 0;
for (i = 0; i < x.length; i++) {
if(x[i].type== "checkbox" && x[i].checked)
cnt++;
}
alert("item selected=" + cnt);