Restricting gridview row selection in asp.net using c#.net - javascript

I have textbox and gridview(checkbox in Itemtemplate) in my webform.
my requirement selecting checkbox in gridview must be restricted based on value given in textbox i.e if textbox value is 10 then i can only be able to check 10 rows in gridview.
Can anybody give me javascrit for this or any other easy way....
Thanks in advance..
my code is below...
<script type="text/javascript" >
function CheckBoxCount() {
var gv = document.getElementById("<%= GridView1.ClientID %>");
var inputList = gv.getElementsByTagName("input");
var textboxcount = document.getElementById("<%=txtId.ClientID %>").value;
var numChecked = 0;
for (var i = 0; i < inputList.length; i++)
{
if (inputList[i].type == "checkbox" && inputList[i].checked)
{
alert(numChecked);
if (numChecked < textboxcount)
{
inp[i].checked = false;
alert(numChecked);
}
numChecked = numChecked + 1;
}
}
}
</script>
I am trying in javascript
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate >
<asp:CheckBox ID="chb" runat="server" AutoPostBack="true" onClick="CheckBoxCount()" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

I can't give you the JS right away but try doing it this way.
put a class on your text box and check box, And then:
<asp:CheckBox ID="chb" runat="server" AutoPostBack="true" onClick="CheckBoxCount()" CssClass="MyCheckBox" />
Then in the javascript add a function onClick of checkBox:
$('.MyCheckBox').onClick(function(){
var $allCheckBoxes = $('#GridView1').find('.MyCheckBox');
var checkedCheckBoxes = 0;
var allowedCheckBoxes = $('.NumberOfCheckBoxesClass').val();
$allCheckBoxes.each(
if($(this).Checked){
checkedCheckBoxes++;
}
);
if(checkedCheckBoxes > 10){
$(this).disable;
AND SHOW SOME MESSAGE letting the user know.
}
});
You obviously need a few more methods to disable all the
Let me know if you have any questiongs.

Related

Jquery each function not execute inside gridview textbox in asp.net

Here is my gridview
<asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle"
AutoGenerateColumns="False" Width="100%" EmptyDataText="No record found" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="Amount" HeaderText="Amount"></asp:BoundField>
<%--<asp:BoundField DataField="PaidAmount" HeaderText="Paid Amount"></asp:BoundField>--%>
<asp:TemplateField HeaderText="Paid Amount">
<ItemTemplate>
<asp:TextBox ID="txtPaidAmount" type="text" runat="server" Text='<%# Eval("PaidAmount") %>' CssClass='<%# "txtDoctorPaidAmount "+"txtDPPaidAmount_"+Eval("AdmissionId") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using j query each function of my gridview textbox class,but jquery each function not executing,here is my code
$(".txtDoctorPaidAmount").on('keyup change', function () {
debugger;
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
sum += parseFloat($(this).text());
});
$("#txtPaidAmount").val(sum.toFixed(2));
});
this each function not executing,how to solve this?
Try this: Use val() instead of text() and add a console.log to see, if iteration is executed.
$(".txtDoctorPaidAmount").on('keyup change', function () {
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
// use val instead of text
let inputVal = $(this).val();
// this line is just to show, that each is executed
console.log('adding value: ' + inputVal);
sum += parseFloat(inputVal);
});
$("#txtPaidAmount").val(sum.toFixed(2));
});

Searching Records from gridview based on value enterd into TextBox

I am trying to Search records from gridview with pagination, matching with the values entered into textbox, and its working quite fine. Issue is that it only show the records which are at first page , but not search the records from the next pages.
aspx code:
<asp:GridView ID="GrdFutureApt" AutoGenerateColumns="false" runat="server" CssClass="table table-responsive table-condensed table-bordered table-striped" AllowPaging="true"
CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5" OnPageIndexChanging="GrdFutureApt_PageIndexChanging">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientName" HeaderText="Patient Name" Visible="false"/>
<asp:BoundField DataField="DoctorName" HeaderText="Doctor Name"/>
<asp:BoundField DataField="AppointmentDate" HeaderText="Appointment Date" DataFormatString="{0:dd/MM/yyyy}"/>
<asp:TemplateField HeaderText = "Appointment Time" SortExpression="Time">
<ItemTemplate>
<asp:Label runat="server" ID="lblAppointmentTime" Text='<%# DisplayAs12HourTime(Eval("AppointmentTime")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AppoinmentStatus" HeaderText="Status"/>
</Columns>
<PagerSettings Mode="NextPrevious" PreviousPageText="Previous" NextPageText=" Next" Position="Bottom" />
<PagerStyle BackColor="#889FA2" HorizontalAlign="Left" ForeColor="White" Font-Bold="true" />
</asp:GridView>
I have used Following script to perform this function.
<script type="text/javascript">
$(document).ready(function () {
$('#<%=txtSearchBox.ClientID %>').keyup(function (e) {
SearchGridData();
});
});
function SearchGridData() {
var counter = 0;
//Get the search text
var searchText = $('#<%=txtSearchBox.ClientID %>').val().toLowerCase();
//Hide No record found message
$('#<%=lblMsgFail.ClientID %>').hide();
//Hode all the rows of gridview
$('#<%=GrdAppointments.ClientID %> tr:has(td)').hide();
if (searchText.length > 0) {
//Iterate all the td of all rows
$('#<%=GrdAppointments.ClientID %> tr:has(td)').children().each(function () {
var cellTextValue = $(this).text().toLowerCase();
//Check that text is matches or not
if (cellTextValue.indexOf(searchText) >= 0) {
$(this).parent().show();
counter++;
}
});
if (counter == 0) {
//Show No record found message
$('#<%=lblErrorMsg.ClientID %>').show();
}
}
else {
//Show All the rows of gridview
$('#<%=lblErrorMsg.ClientID %>').hide();
$('#<%=GrdAppointments.ClientID %> tr:has(td)').show();
}
}
</script>
And using following javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
the data to fill gridview comes from the following function:
public void LoadGrid()
{
S011AppointmentBOL objBol = new S011AppointmentBOL();
//DataTable ptApt = new DataTable();
dtAppointment = S011AppointmentBLL.GetAll();
int patID = dtPatient.AsEnumerable().Where(x => x.Field<string>("RegistrationNo") == RegNo).Select(x => x.Field<int>("PatientID")).FirstOrDefault();
dtAppointment.Columns.Add("PatientName", typeof(string));
dtAppointment.Columns.Add("DoctorName", typeof(string));
for (int i = 0; i < dtAppointment.Rows.Count; i++)
{
string pFname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string pLname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
string dFname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string dLname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
dtAppointment.Rows[i]["PatientName"] = pFname + " " + pLname;
dtAppointment.Rows[i]["DoctorName"] = dFname + " " + dLname;
}
DataTable boundTable = new DataTable();
var query = dtAppointment.AsEnumerable().Where(x => x.Field<int>("PatientID") == patID).Select(x => x).OrderByDescending(x => x.Field<DateTime>("AppointmentDate"));
var t = query.Any();
if (t)
{
boundTable = query.CopyToDataTable<DataRow>();
}
GrdAppointments.DataSource = boundTable;
GrdAppointments.DataBind();
}
And On every keyup I don't want query to database that's why am using the Datatable to fill gridview
Any Help Appreciated.. Thanks
You have enabled paging for Gridview so it will bind only records from selected pages on client side.So you have to either disable paging or rewrite jquery search function by calling a webmethord to search entire records which can bind search results.

How to check/uncheck Gridview check box for outside button

How do I toggle the gridview check box from a button? I want to use Javascript only.
I am using below code for grid view:
<asp:GridView ID="gvWrkLogVW" runat="server" AutoGenerateColumns="False" GridLines="None" BorderStyle="None" ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkWorklog" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="The_Text" />
</Columns>
</asp:GridView>
I want to access the code gridview checkbox from external button
<asp:Button ID="btncheck" runat="server" Text="Check All" OnClientClick="SelectAll()" />
I am writing the below javascript but it is not working
function SelectAll() {
var gridViewControl = document.getElementById('<%= gvGetAllCircuits.ClientID %>');
for (i = 0; i < gridViewControl.rows.length; i++) {
if (gridViewControl.elements[1].type == "checkbox") {
gridViewControl.elements[1].checked = true;
}
}
}
JS
function SelectAll() {
var gridViewControl = document.getElementById('<%= gvGetAllCircuits.ClientID %>');
for (i = 0; i < gridViewControl.rows.length; i++) {
//loop starts from 1. rows[0] points to the header.
for (i=1; i<gridViewControl.rows.length; i++)
{
//get the reference of first column - if you have a header
cell = gridViewControl.rows[i].cells[0];
//loop according to the number of childNodes in the cell
for (j=0; j<cell.childNodes.length; j++)
{
//if childNode type is CheckBox
if (cell.childNodes[j].type =="checkbox")
{
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = "true";
}
}
}
}
}

Disable file upload control using JavaScript

How can i disable or enable File upload control of .NET framework using Javascript??
Does any one have idea, please help.
Thanks in advance.
Try doing this:
<script type = "text/javascript">
function EnableDisable(rbl) {
var rb = rbl.getElementsByTagName("input");
document.getElementById("<%=FileUpload1.ClientID %>").disabled = true;
for (var i = 0; i < rb.length; i++) {
if (rb[i].value == 1 && rb[i].checked) {
document.getElementById("<%=FileUpload1.ClientID %>").disabled = false;
}
}
}
</script>
<form runat = "server">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" onclick = "EnableDisable(this)">
<asp:ListItem Text = "Yes" Value = "1"></asp:ListItem>
<asp:ListItem Text = "No" Value = "2"></asp:ListItem>
</asp:RadioButtonList>
<asp:FileUpload ID="FileUpload1" runat="server" disabled = "disabled"/>
</form>
Use
document.getElementById(FileUploadControlID).disabled = true;

How to enable and disable CheckBox in the GridView using JavaScript?

I have a GridView "gvpodetails". In that I have two checkboxes one in the first column of the GridView and another one in the last column of the GridView.
I want to enable the second checkbox when the first checkbox is checked.
And I want to disable the second checkbox when the first checkbox is unchecked.
I have wirtten the following JavaScript.
var grid = document.getElementById('<%=gvPODetails.ClientID %>');
var PlannedQty = 0*1;
if(grid != null)
{
var Inputs = grid.getElementsByTagName('input');
for(i = 0;i < Inputs.length;i++)
{
var id=String(Inputs[i].id);
if(Inputs[i].type == 'text' && id.indexOf("txtPlannedQuantity")!=-1)
{
if(Inputs[i-2].type == 'checkbox')
{
if(Inputs[i-2].checked)
{
if(Inputs[i+2].value == "0.000")
Inputs[i+2].value = (parseFloat(Inputs[i].value) - parseFloat(Inputs[i+1].value))
else
Inputs[i+2].value = Inputs[i+2].value;
Inputs[i+2].disabled = false;
Inputs[i+3].disabled = false;
Inputs[i-1].disabled = false;
Inputs[i+6].disabled = false;// This is for Second CheckBox
}
else
{
Inputs[i+4].value="0.00";
Inputs[i+5].value="0.00";
Inputs[0].checked = false;
Inputs[i+2].disabled = true;
Inputs[i+3].disabled = true;
Inputs[i-1].disabled = true;
Inputs[i+6].disabled = true;// This is for Second CheckBox
}
}
}
}
}
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal();" /></ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onclick="CheckAll();" /></HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ED_f">
<ItemTemplate>
<asp:CheckBox ID="chkEDInclusive" runat="server" Checked = '<%#Bind("EDInclusive_f") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
These are my javascript and GridView source code.
I also has some textboxes in the template field columns. This condition is applicable to all the textboxes in the GridView.
But the TextBoxes are enabled and disabled properly except the last CheckBox.
I have given only the Source code for the two Checkboxes only.
How to enable and disable the last checkbox in the GridView when the first the CheckBox is checked and Unchecked?
I need all your suggestions please..
You should probably use event delegation. on the grid to do this.
This javascript assumes that your row tag name is 'tr' and that your second checkbox is input[1] when selecting all inputs of that particular row. If you need IE support you'd need to use your favorite event handling wrapper.
window.onload = function () {
var rowNodeName = 'tr',
firstInputClassName = 'foo';
document.getElementById('<%=gvPODetails.ClientID %>').addEventListener('change', function (e) {
if (e.target.type === 'checkbox' && e.target.className.match(firstInputClassName)) {
// Find parent row
var row = e.target.parentNode;
while (row.nodeName !== rowNodeName.toUpperCase()) {
row = row.parentNode;
if (!row) {
break; // In case we hit document
}
}
if (row) {
var inputs = row.getElementsByTagName('input');
inputs[1].disabled = !e.target.checked;
}
}
}, false);
}
This will handle change events on any input in the grid with a className of 'foo' as defined in the firstInputClassName variable. When triggered will walk up the dom tree to a node with a tagname equalling rowNodeName, select the inputs in that row and set the disabled status of the second input in that row opposite of the checked state of the input that triggered the event.

Categories

Resources