Hide/Show Button based on status if row selected - Javascript - javascript

I hope I can be of help. I could not find anything like this in javascript.
I did in C # code, but I could use in Javascript for faster page and related transactions.
My situation is this:
I have to hide or display two buttons depending on the choice of a selected line taking into account the value of a particular field.
How to bring it in Javascript?
For now I've done this:
<script type="text/javascript">
function cbCheck_CheckedChanged()
{
List<object> ListStatoIns = new List<object>();
try
{
if (ListStatoIns != null)
{
if (ListStatoIns.Exists(x => x.Equals(true)) && ListStatoIns.Exists(x => x.Equals(false)))
{
btnApriInserimenti.style.display = "block";
btnChiudiInserimenti.style.display = "block";
}
else if (!ListStatoIns.Exists(x => x.Equals(true)))
{
btnChiudiInserimenti.style.display = "none";
btnChiudiInserimenti.style.display = "block";
}
else if (!ListStatoIns.Exists(x => x.Equals(false)))
{
btnChiudiInserimenti.style.display = "block";
btnChiudiInserimenti.style.display = "none";
}
}
}
catch (err) { }
}
</script>
This is Grid:
<cap:MultiColumnSortingGridView ID="gvDettaglio" runat="server" CssClass="grid-view"
DataKeyNames="Organizzazione,OrgID,Mensilita,CodiceOrg,isCaricamentoCompletato"
EmptyDataText="Non sono presenti dati inspezionabili: controlla la mensilità di riferimento o lo stato della contabilità" AutoGenerateColumns="false"
ExportButtonCssClass="button BtnExportExcel" ExportFileName="Dettaglio Straordinario">
<Columns>
<asp:TemplateField ItemStyle-Width="40">
<HeaderTemplate>
<asp:CheckBox ID="cbCheckAll" runat="server" Checked="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbCheck" runat="server" CssClass='<%# Eval("isCaricamentoCompletato")%>'
ToolTip="Seleziona per la riapertura o la chiusura dell'inserimento"
AutoPostBack="true" onclick="javascript:gvDettaglio.Rows(cbCheck_CheckedChanged);"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="40">
<ItemTemplate>
<span class="jTooltipR button BtnAudit" title='<%# PrintOperazione(Eval("_ultimo"), Eval("_ultima")) %>'></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mensilita di pagamento">
<ItemTemplate>
<%# PrintMensilita(CNA.CommonLib.Util.ConversionUtil.ConvertInt32orDefault(Eval("Mensilita"))) %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CodiceOrg" HeaderText="Codice" SortExpression="CodiceOrg" />
<asp:BoundField DataField="OrgID" HeaderText="Id Org." Visible="false" />
<asp:BoundField DataField="Organizzazione" HeaderText="Organizzazione" SortExpression="Organizzazione" />
<asp:BoundField DataField="NrDipendenti" HeaderText="Militari al BTG/RGT" SortExpression="NrDipendenti" />
<asp:BoundField DataField="NrDipInteressati" HeaderText="Mil. con Str." SortExpression="NrDipInteressati" />
<asp:BoundField DataField="NrJobMassivi" HeaderText="File inseriti" SortExpression="NrJobMassivi" />
<asp:BoundField DataField="NrJobElaborazioni" HeaderText="Militari inseriti" SortExpression="NrJobElaborazioni" />
<asp:TemplateField ItemStyle-Width="20">
<ItemTemplate>
<span class="jTooltipL buttonLittle BtnInfoLittle" title='<%# PrintTotaleDet(Eval("Totale")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Totale Ore">
<ItemTemplate>
<%# PrintTotale(Eval("Totale")) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stato Inserimento" SortExpression="isCaricamentoCompletato">
<ItemTemplate>
<label class='<%# Eval("isCaricamentoCompletato").Equals(true) ? "validatedNotItem" : "validatedItem"%>'
style="width: 40px!important;"
title='<%#Eval("isCaricamentoCompletato").Equals(true) ? "Caricamento Chiuso" : "Caricamento Aperto"%>'>
</label>
<%--<span class="jTooltipL buttonLittle BtnInfoLittle" title= '<%#Eval("isCaricamentoCompletato").Equals(true) ? "Caricamento Chiuso" : "Caricamento Aperto"%>' />--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="40" HeaderText="Dettaglio">
<ItemTemplate>
<asp:LinkButton CausesValidation="false" ID="btnExportExcel" runat="server"
CssClass="button BtnExportExcel" Width="40" CommandName="Report" OnClick="OnClikDettaglioStraordinario"
Visible='<%# !String.IsNullOrEmpty(PrintTotale(Eval("Totale"))) %>'
ToolTip='Dettaglio straordinari inseriti' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cap:MultiColumnSortingGridView>
Who helps me? many thanks in advance

Related

Check/Unchek asp checkbox

I want to check and uncheck several ASP checkboxes with the event of other ASP checkbox.
I want that the checkbox with ID "chkSelecAllGtias" can check and uncheck the checkboxes of the "GridView" with the ID "chkSeleccionarGtia"
Here my ASP code:
<div id="divGtiasLn" runat="server">
<div class="formRow" id="tLineasG" style="padding:10px 20px 20px 20px">
<label style="font-weight:bold">Título de la cabecera</label>
<div class="BotonesOpcion AlineaDerecha">
<div class="label">
Seleccionar Todas
<asp:CheckBox id='chkSelecAllGtias' runat='server'></asp:CheckBox>
</div>
</div>
<div style="width:100%;max-height:350px;overflow:auto">
<asp:GridView ID="rgDatosGtias" runat="server" AutoGenerateColumns="false" EmptyDataText="No se encontraron" DataKeyNames="DataField1,DataField2,DataField3,DataField4" AlternatingRowStyle-BackColor="#DAE2E8">
<Columns>
<asp:TemplateField HeaderText="Seleccionar">
<ItemTemplate>
<asp:CheckBox ID="chkSeleccionarGtia" runat="server" AutoPostBack="true" OnCheckedChanged="chkSeleccionarGtia_Check" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DataField1" HeaderText="Número1" />
<asp:BoundField DataField="DataField2" HeaderText="Número2" Visible="false" />
<asp:BoundField DataField="DataField3" HeaderText="Número3" />
<asp:BoundField DataField="DataField4" HeaderText="Número4" />
<asp:BoundField DataField="DataField5" HeaderText="Número5" />
<asp:BoundField DataField="DataField6" HeaderText="" Visible="false" />
<asp:BoundField DataField="DataField7" HeaderText="" Visible="false" />
<asp:BoundField DataField="DataField8" HeaderText="" Visible="false" />
</Columns>
</asp:GridView>
</div>
</div>
</div>
My C# code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
chkSelecAllGtias.Attributes.Add("OnClick", "SeleccionarTodasGtias();");
}
catch (Exception ex)
{
msjError.MostrarInfo(ex.InnerException.Message);
}
}
And my JS code:
function SeleccionarTodasGtias() {
console.log("Dentro");
$('#chkSeleccionarGtia').prop('checked', true);
$('#chkSeleccionarGtia').prop('checked', false);
$('#chkSelecAllGtias').prop('checked', true);
$('#chkSelecAllGtias').prop('checked', false);
//$('<=chkSelecAllGtias.ClientID%>').attr('checked', false);
//var objState1 = $find("<%= chkSelecAllGtias.ClientID %>");
console.log("objState1 -> " + objState1);
if (document.getElementById('chkSelecAllGtias').checked == true) {
document.getElementById('chkSeleccionarGtia').checked = true;
alert("true");
}
else {
document.getElementById('chkSeleccionarGtia').checked = false;
alert("false");
}
}
I have tried with only JS but it did not work.
And some combinations of this:
$("#Checkbox1").prop('checked', true); //// To check
$("#Checkbox1").prop('checked', false); //// To un check
And it didn't work
You can do it like this (my example has check box at botton, but it don't matter.
So, this:
<asp:CheckBox id='chkSelecAllGtias' runat='server'
onclick="myheadcheck(this)" >
</asp:CheckBox>
<script>
function myheadcheck(btn) {
// get the ONE check box, checked, or not???
var bolChecked = $(btn).is(':checked')
// now set all check boxes
MyTable = $('#<%= grdEmp.ClientID %>') // select and get grid
MyCheckBoxs = MyTable.find('input:checkbox') // select all check boxes in grid
MyCheckBoxs.each(function () {
$(this).prop('checked', bolChecked)
})
}
</script>
So, I don't have your data, but say I have this gridview, and then a check box.
So, this:
<h3>Select Hotels</h3>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-hover" width="50%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:CheckBox ID="chkHeader" runat="server" Text="Select/unselect All" onclick="myheadcheck(this)" />
<script>
function myheadcheck(btn) {
// get the ONE check box, checked, or not???
var bolChecked = $(btn).is(':checked')
// now set all check boxes
MyTable = $('#<%= GridView1.ClientID %>') // select and get grid
MyCheckBoxs = MyTable.find('input:checkbox') // select all check boxes in grid
MyCheckBoxs.each(function () {
$(this).prop('checked', bolChecked)
})
}
</script>
Code to load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
}
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And now we get/see this:
function CheckAll() {
var chk = $(".chkall").prop("checked");
$("<checkbox name> input:checkbox").each(function (index, item) {
$(item).prop("checked", chk);
});
}

Javascript sum grandtotal returning NaN error

I am using below JavaScript code to get row totals and grand total of gridview
but the issue is grand total which is $mult returns NaN
out put i get
Item Name Unit Price UOM Quantity Total Amount
item1 5.00 pcs 2 10.00
item2 10.00 pcs 3 30.00
NaN
JavaScript
<script>
$(document).ready(function () {
$(".txtMult input").on('keyup mouseup', multInputs);
function multInputs() {
var $mult = 0;
$("tr.txtMult").each(function () {
var $UnitPrice = $('.UnitPrice', this).val();
var $Quantity = $('.Quantity', this).val();
var $total = (($UnitPrice) * ($Quantity));
$mult += $total;
});
$("tr.txtMult").each(function () {
var $UnitPrice = $('.UnitPrice', this).val();
var $Quantity = $('.Quantity', this).val();
$('.multTotal', this).text(parseFloat($total).toFixed(3));
});
$(".lblGrandAmount").text(parseFloat($mult).toFixed(3));
}
});
</script>
Grid-view
<asp:GridView ID="griditem" OnRowDataBound="griditem_RowDataBound" CssClass="table" GridLines="None" runat="server" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSel" Checked="true" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" SortExpression="Item Name" />
<asp:TemplateField HeaderText="Unit Price" SortExpression="UnitPrice">
<ItemTemplate>
<asp:TextBox ID="txtCalcUnitprice" TextMode="Number" step="any" Width="120" CssClass="form-control UnitPrice" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="UOM" SortExpression="UOM" />
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtCalcQty" Width="120" TextMode="Number" min="0" step="any" CssClass="form-control Quantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Amount">
<ItemTemplate>
<asp:Label ID="lbltotalamount" CssClass="multTotal" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblgrandamount" CssClass="lblGrandAmount" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemID" HeaderText="ItemID" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" SortExpression="ItemID" />
</Columns>
</asp:GridView>
What could be the issue that makes this error occur?
All trs have the class txtMult, so you need to exclude header tr and grand total tr from the calculation. You can use :gt(0) and :lt(-1) for this like following.
$(".txtMult input").on('keyup mouseup', multInputs);
function multInputs() {
var $mult = 0;
$("tr.txtMult:gt(0):lt(-1)").each(function () {
var $UnitPrice = $('.UnitPrice', this).val();
var $Quantity = $('.Quantity', this).val();
var $total = $UnitPrice * $Quantity;
$mult += $total;
$('.multTotal', this).text($total.toFixed(2));
});
$(".lblGrandAmount").text($mult.toFixed(2));
}

Check Box to be selected row index manner in gridview

I want to select the check box values in row index manner in a grid view, Can someone suggest how to select the checkbox? Please find below the code not working appropraitely.
function Check_Click(spanChk) {
{
var IsChecked = spanChk.checked;
var Chk = spanChk;
Parent = document.getElementById('Gv1');
var btn = document.getElementById('<%=btnsubmit.ClientID %>');
var items = Parent.getElementsByTagName('input');
var i = 0;
var tot = 0;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
items[i].checked = false;
return;
}
}
}
}
}
This is my grid view file
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gv1_RowDataBound">
<Columns>
<asp:BoundField DataField="datedif" HeaderText="Day/Hour" SortExpression="datedif" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Enabled='<%# Eval("hour1").ToString().Equals("False") %>' OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Enabled='<%# Eval("hour2").ToString().Equals("False") %>' OnCheckedChanged="CheckBox6_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" Enabled='<%# Eval("hour3").ToString().Equals("False") %>' OnCheckedChanged="CheckBox3_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox4" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox4" runat="server" Enabled='<%# Eval("hour4").ToString().Equals("False") %>' OnCheckedChanged="CheckBox4_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox5" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox5" runat="server" Enabled='<%# Eval("hour5").ToString().Equals("False") %>' OnCheckedChanged="CheckBox5_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Call the JavaScript function from all of the CheckBoxes as shown below,
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gv1_RowDataBound">
<Columns>
<asp:BoundField DataField="datedif" HeaderText="Day/Hour" SortExpression="datedif" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn1" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Enabled='<%# Eval("hour1").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox1_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="ChkColumn2" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Enabled='<%# Eval("hour2").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox6_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn3" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Enabled='<%# Eval("hour3").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox3_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn4" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Enabled='<%# Eval("hour4").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox4_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn5" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Enabled='<%# Eval("hour5").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox5_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the JavaScript, validate the selected CheckBox with its Row and then validate the number of items selected.
function IdExists(elements, id) {
for (var i = 0; i < elements.length; i++) {
if (elements[i].id.indexOf(id) > -1) {
return true;
}
}
return false;
}
function Check_Click(chkBx) {
Parent = document.getElementById('<% =Gv1.ClientID %>');
for (i = 0; i < Parent.rows.length; i++) {
var row = Parent.rows[i];
var items = row.getElementsByTagName('input');
if (items.length > 0) {
if (IdExists(items, chkBx.id)) {
var tot = 0;
for (j = 0; j < items.length; j++) {
if (items[j].type == 'checkbox' && items[j].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
chkBx.checked = false;
return;
}
}
}
}
}
}
}
You need to add a class name in the checkbox. then you can easily get all the checkbox by the class name.
function Check_Click(spanChk) {
{
var IsChecked = spanChk.checked;
var items = document.getElementsByClassName('myCheckBox');
var i = 0;
var tot = 0;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
items[i].checked = false;
return;
}
}
}
}
}
UPDATE:
you can also use the below code to get all the checkbox.
var Checkboxes = document.querySelectorAll('input[type=checkbox]');

Insert data from grid view to sql server

I am doing project on asp.net. Right now I have got problem with insert data from gridview to sql server. In my gridview I have add a template as a textbox in order to input value. My problem is about insert value from textbox of gridview to sql server. My code as below:
<%# Page Title="" Language="C#" MasterPageFile="~/coca.Master" AutoEventWireup="true" CodeBehind="Orders.aspx.cs" Inherits="AssignmentWeb.Orders" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="center">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=txtQty]").val("0");
});
$("[id*=txtQty]").live("change", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$("[id*=txtQty]").live("keyup", function () {
if (!jQuery.trim($(this).val()) == '') {
if (!isNaN(parseFloat($(this).val()))) {
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
}
} else {
$(this).val('');
}
var grandTotal = 0;
$("[id*=lblTotal]").each(function () {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
</script>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="AverageProduct" HeaderText="AverageProduct" SortExpression="AverageProduct" ItemStyle-CssClass="price"/>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="QtyOrder">
<ItemTemplate>
<asp:Textbox ID="txtQty" runat="server"></asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Grand Total:
<asp:Label ID="lblGrandTotal" runat="server" Text="0"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:InventoryRouting %>" SelectCommand="SELECT [ProductName], [AverageProduct], [Description], [ProductID] FROM [Product]"></asp:SqlDataSource>
<br />
<asp:Button ID="btnOrder" runat="server" Text="Order!" Width="100px" OnClick="btnOrder_Click"/>
<br />
<br />
</div>
</asp:Content>
<script runat="server">
public void btnOrder_Click(object sender, EventArgs e)
{
int c = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("Data Source=LIDA-PC; Initial Catalog=InventoryRouting; Integrated Security=True");
//cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID, #ProductName, #QtyOrder, #Total)";
cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID , #ProductName, #QtyOrder, #Total)";
cmd.Connection .Open();
//cmd.Parameters.AddWithValue("'" + Session["Username"].ToString() + "'", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#ProductID", GridView1.Rows[i].Cells[0].Text);
cmd.Parameters.AddWithValue("#ProductName", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#QtyOrder", GridView1.Rows[i].Cells[4].Text);
cmd.Parameters.AddWithValue("#Total", GridView1.Rows[i].Cells[5].Text);
//InsertCommand = new SqlCommand("INSERT INTO [orders] ([client], [product], [amount], [price]) VALUES ('" + Session["Username"].ToString() + "', #ProductName, #AverageProduct, #QtyOrder, #Total)");
cmd.ExecuteNonQuery();
cmd.Connection.Close();
c = c + 1;
}
}
</script>
You need to convert grid view row cell control to the appropriate control explicitly.
access like this ((Textbox)(GridView1.Rows[i].Cells[4].Controls[0]).Text for your #QtyOrder
and ((Label)(GridView1.Rows[i].Cells[5].Controls[0]).Text for #Total.
OR
(GridView1.Rows[i].FindControl("txtQty") as TextBox).Text
Thanks.

CheckBox in HeaderTemplate validates ItemTemplate CheckBox

Question:
I'm trying to validate the dropdownlist if the user checked the checkbox as you can see in the screen one.
Problem:
So, how can I validate the checkbox if the user have select all the checkboxes from header?
as you can see the screen two. if I select all the checkboxes then i am looking to fireup the validate as shown in screen one.
output:
screen 1:
screen 2
//aspx
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" ControlStyle-Width="250px" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="FirstName" ControlStyle-Width="250px" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" ControlStyle-Width="250px" HeaderText="LastName"
SortExpression="LastName" />
<asp:TemplateField HeaderText="Reject">
<HeaderTemplate >
Reject<br />
<asp:CheckBox ID="checkboxall" runat="server" />
<asp:DropDownList ID="drpPaymentMethod_header" runat="server">
<asp:ListItem Value="-1">Please select reason</asp:ListItem>
<asp:ListItem Value="0">Month</asp:ListItem>
<asp:ListItem Value="1">At End</asp:ListItem>
<asp:ListItem Value="2">At Travel</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" CssClass="selectreject" runat="server" />
<asp:DropDownList ID="drpPaymentMethod" runat="server">
<asp:ListItem Value="-1">Please select reason</asp:ListItem>
<asp:ListItem Value="0">Month</asp:ListItem>
<asp:ListItem Value="1">At End</asp:ListItem>
<asp:ListItem Value="2">At Travel</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv" InitialValue="-1" ControlToValidate="drpPaymentMethod" ForeColor="Red" SetFocusOnError="true"
Enabled="false" Display="dynamic" runat="server" ErrorMessage="Please select reason"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txt_Value" runat="server" Width="58px" Text="0"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//cs
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox checkbox1 = e.Row.FindControl("checkbox1") as CheckBox;
RequiredFieldValidator rfv = e.Row.FindControl("rfv") as RequiredFieldValidator;
DropDownList drpPaymentMethod = (DropDownList)e.Row.FindControl("drpPaymentMethod");
// you can just pass "this" instead of "myDiv.ClientID" and get the ID from the DOM element
checkbox1.Attributes.Add("onclick", "UpdateValidator('" + checkbox1.ClientID + "','" + drpPaymentMethod.ClientID + "','" + rfv.ClientID + "');");
if (!checkbox1.Checked)
drpPaymentMethod.Attributes.Add("disabled", "disabled");
}
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox checkboxall = e.Row.FindControl("checkboxall") as CheckBox;
//how to get the reference here ( rfv ?????????)
//checkboxall.Attributes.Add("onclick", "UpdateValidatorAll('" + checkboxall.ClientID + "','" + drpPaymentMethod.ClientID + "','" + rfv.ClientID + "');");
}
}
//js
$(document).ready(function () {
var checkbox1 = "#<%=gv.ClientID%> input[id*='checkbox1']:checkbox";
var checkboxall = $("input[id$='checkboxall']");
$(checkboxall).click(function () {
if (checkboxall.is(':checked')) {
$('.selectreject > input').attr("checked", checkboxall.attr("checked"));
}
else {
$('.selectreject > input').attr("checked", false);
}
});
});
function UpdateValidator(chkID, drpID, validatorid) {
//enabling the validator only if the checkbox is checked
var enableValidator = $("#" + chkID).is(":checked");
if (enableValidator)
$('#' + drpID).removeAttr('disabled');
else
$('#' + drpID).attr('disabled', 'disabled');
var vv = $('#' + validatorid).val();
ValidatorEnable(document.getElementById(validatorid), enableValidator);
}
function UpdateValidatorAll(....) // i havent write the code for this function (select All checkbox)
try this:
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" ControlStyle-Width="250px" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="FirstName" ControlStyle-Width="250px" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" ControlStyle-Width="250px" HeaderText="LastName"
SortExpression="LastName" />
<asp:TemplateField>
<HeaderTemplate>
Reject<br />
<asp:CheckBox ID="checkboxall" runat="server" />
<asp:DropDownList ID="drpPaymentMethod_header" runat="server">
<asp:ListItem Value="-1">Please select reason</asp:ListItem>
<asp:ListItem Value="0">Month</asp:ListItem>
<asp:ListItem Value="1">At End</asp:ListItem>
<asp:ListItem Value="2">At Travel</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" />
<asp:DropDownList ID="drpPaymentMethod" CssClass="gridDropDown" runat="server">
<asp:ListItem Value="-1">----</asp:ListItem>
<asp:ListItem Value="0">Month</asp:ListItem>
<asp:ListItem Value="1">At End</asp:ListItem>
<asp:ListItem Value="2">At Travel</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv" CssClass="gridRfv" InitialValue="-1" ControlToValidate="drpPaymentMethod"
Enabled="false" Display="Static" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txt_Value" runat="server" Width="58px" Text="0"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" />
CS:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox checkbox1 = e.Row.FindControl("checkbox1") as CheckBox;
RequiredFieldValidator rfv = e.Row.FindControl("rfv") as RequiredFieldValidator;
DropDownList drpPaymentMethod = (DropDownList)e.Row.FindControl("drpPaymentMethod");
// you can just pass "this" instead of "myDiv.ClientID" and get the ID from the DOM element
checkbox1.Attributes.Add("onclick", "UpdateValidator('" + checkbox1.ClientID + "','" + drpPaymentMethod.ClientID + "','" + rfv.ClientID + "');");
if (!checkbox1.Checked)
drpPaymentMethod.Attributes.Add("disabled", "disabled");
}
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox checkboxall = e.Row.FindControl("checkboxall") as CheckBox;
checkboxall.Attributes.Add("onclick", "UpdateValidatorAll('" + checkboxall.ClientID + "');");
}
}
JavaScript:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function UpdateValidator(chkID, drpID, validatorid) {
//enabling the validator only if the checkbox is checked
var enableValidator = $("#" + chkID).is(":checked");
if (enableValidator)
$('#' + drpID).removeAttr('disabled');
else
$('#' + drpID).attr('disabled', 'disabled');
var vv = $('#' + validatorid).val();
ValidatorEnable(document.getElementById(validatorid), enableValidator);
}
function UpdateValidatorAll(chkID) {
//enabling the validator only if the checkbox is checked
var enableValidator = !$("#" + chkID).is(":checked");
$('.gridDropDown').each(function (index) {
if (enableValidator)
$(this).removeAttr('disabled');
else
$(this).attr('disabled', 'disabled');
});
$('.gridRfv').each(function (index) {
var cont = $(this).get();
ValidatorEnable(cont[0], enableValidator);
});
}
</script>

Categories

Resources