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.
Related
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);
});
}
I have a gridview and scenario is: once someone deletes a row, it checks if NOTIF_RECIP_SEQ_NBR is maximum or not. If yes then it deletes that row else give a popup.
So basically once someone click on delete, it gets the NOtif_recip_Id of that row and iterates through Gridview to see if NOTIF_RECIP_SEQ_NBR of any row corresponding to that NOTIF_RECIP_ID is greater or not.
Question is It possible at client side? I did it with server side but I don't think that's a good way when I have all data on client side itself.
Please help. I tried multiple ways with Javascript but no use.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function check(var a ,var b)
{
var grid = document.getElementById("GridView1");
var cellPivot;
debugger;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++)
{
//here I want code to iterate and compare value.Is it possible?
alert("You must select an answer for all columns if Pivot is yes")
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label13" runat="server" Text="Notif_Recip Data" BackColor="Azure"></asp:Label>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="NOTIF_RECIP_GUID" emptydatatext="There are no data records to display."
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor="Beige"
HeaderStyle-BackColor = "AppWorkspace"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "NOTIF_RECIP_ID">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="v1txtNOTIF_RECIP_ID" runat="server" ControlToValidate="txtNOTIF_RECIP_ID" Text="?" ForeColor="Red" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "NOTIF_RECIP_SEQ_NBR">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_SEQ_NBR" runat="server"
Text='<%# Eval("NOTIF_RECIP_SEQ_NBR")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("NOTIF_RECIP_GUID")%>'
OnClientClick = "ValidateGrid"
Text = "Delete" OnClick = <%# "javascript:check('" + Eval("NOTIF_RECIP_SEQ_NBR")" + "Eval("NOTIF_RECIP_ID") + "')" %> ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<HeaderStyle Font-Bold="True" />
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I found the solution so pasting for anyone who in need.
<script type = "text/javascript">
function GetSelectedRow(lnk) {
debugger;
var table, tbody, i, rowLen, row, j, colLen, cell;
var result = confirm('Do you want to delete this value ?');
if (result) {
var x = document.getElementById('Label100');
table = document.getElementById("GridView1");
tbody = table.tBodies[0];
var bool = true;
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var RecipID = row.cells[0].innerText;
var Sqqno = parseInt(row.cells[1].innerText);
for (i = 1, rowLen = tbody.rows.length; i < rowLen; i++) {
row = tbody.rows[i];
var newrecipId = row.cells[0].innerText;
if (newrecipId == RecipID) {
cell = row.cells[1];
var newseq = parseInt(row.cells[1].innerText);
if (Sqqno < newseq) {
// debugger;
bool = false;
x = document.getElementById('Label100');
x.innerHTML = "ERROR-Delete RecipId with max Seqnumber";
x.style.display = "block";
return bool;
break;
}
}
else {
bool = true;
}
}
return bool;
}
else {
return false;
}
}
</script>
I am creating a dashboard and I was able to save information to my database using jQuery, JSON, and a generic handler. Now, I was able to call back my database information using a WebService and JSON. My database information looks like this..
On document ready, I use this to retrieve the information from my table from JSON
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
dataType: "json",
success: function (response) {
var te = response;
function sortResults(prop, asc) {
te.d = te.d.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
sortResults('SortNo', true);
for (var i = 0; i < te.d.length; i++) {
$('#test ul').append('<li>' + te.d[i].Title + '</li>');
console.log(te.d[i])
}
},
error: function (repo) {
console.log(repo);
$("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
}
});
I was helped with the above.. and for testing purposes, this was added to the HTML
<div id="test">
<ul>
</ul>
</div>
And this is what is displayed.
So what is happening, it's ordered by the SortNo and the title of the widgets are displayed. The first 3 are in SortNo 0, and so on. This has really helped me with passing the JSON. Here is what my dashboard looks like..
And this is what my aspx page looks like (only a single 'column' to get an idea)
<div class="column" id="column1" runat="server">
<div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Current Deals per Location</h2>
<div class="dragbox-content">
<asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False"
DataKeyNames="InternallocationID" BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" Width="100%">
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("InternallocationID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("LocationName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Count" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblCount" runat="server" Text="totes"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</div>
<div class="dragbox" id="StorePayrollWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Store's Payroll</h2>
<div class="dragbox-content">
<asp:DropDownList ID="ddlPayrollStores" runat="server" OnSelectedIndexChanged="ddlPayrollStores_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:UpdatePanel ID="UpdatePanelPayroll" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlPayrollStores" EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger>
</Triggers>
<ContentTemplate>
<div class="dragbox-content">
<asp:Label ID="lblLabelOverTime" runat="server" Text="Total Overtime Hours: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalOvertime" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelHoliday" runat="server" Text="Total Holiday: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalHoliday" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelVacation" runat="server" Text="Total Vacation: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalVacation" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lbllableTotalHours" runat="server" Text="Total Hours: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalStoreHours" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelPay" runat="server" Text="Total Pay: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalPay" runat="server" Text=""></asp:Label>
<br />
<br />
<div style="align-content: center">
<asp:LinkButton ID="lbDetailed" runat="server" Text="Detailed Report" PostBackUrl="~/Reporting/Payroll/StorePayroll.aspx"></asp:LinkButton>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<div class="dragbox" id="ObjectiveWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Store Objectives-<asp:HyperLink ID="hlDaily" runat="server" NavigateUrl="~/Reporting/DailyReports/SalesByModel.aspx">Daily Report</asp:HyperLink></h2>
<div class="dragbox-content">
<asp:UpdatePanel ID="upObjective" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlNewUsed" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<div style="width: 100%">
<div style="text-align: center">
<asp:Label ID="lblObjNotice" runat="server" Text="Notice: If your dealership is in red; monthly objectives need updated!" Font-Bold="true" ForeColor="Red"></asp:Label>
<br />
<asp:DropDownList ID="ddlObjDealership" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlObjDealership_SelectedIndexChanged" Style="height: 22px">
</asp:DropDownList>
<asp:DropDownList ID="ddlNewUsed" runat="server" OnSelectedIndexChanged="ddlNewUsed_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>New</asp:ListItem>
<asp:ListItem>Used</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlObjectiveMake" runat="server" Width="155px" OnSelectedIndexChanged="ddlObjectiveMake_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</div>
<table style="display: inline-block; width: 45%">
<tr>
<td style="width: 100%">
<asp:Label ID="lblCommitObj" runat="server" Text="Commit OBJ: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitObj" runat="server" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Label ID="lblCommitGross" runat="server" Text="Commit Gross OBJECT: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitGross" runat="server" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Button ID="btnSubmitDaily" runat="server" Text="Submit" Height="32px" OnClick="btnSubmitDaily_Click" Width="68px" />
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Label ID="lblDailyMess" runat="server"></asp:Label>
</td>
</tr>
</table>
<table style="float: right; width: 45%" title="Current Monthly Objectives">
<caption>
<asp:Label ID="lblTitle" runat="server" Font-Bold="true" Font-Size="Small" Text="Current Monthly Objectives"></asp:Label></caption>
<tr>
<td style="text-align: center">
<br />
<asp:Label ID="lblObj" runat="server" Font-Bold="true" Text="Obj: "></asp:Label>
<br />
<br />
<br />
<asp:Label ID="lblCurrentObj" runat="server" Text=""></asp:Label>
</td>
<td style="text-align: center">
<br />
<asp:Label ID="lblGross" runat="server" Font-Bold="true" Text="Gross: "></asp:Label>
<br />
<br />
<br />
<asp:Label ID="lblCurrentGross" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
I use this jQuery to drag and drop the widgets..
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
stop: function (event, ui) {
updateWidgetData();
}
})
.disableSelection();
});
My question is, how do I position the div's with the same id as the widgets name in document ready? For example, the div with the id CurrentDealsWidget is the first record in the table, with SortNo: 0, ColumnId: 1, Collapsed: 0, and UserId: 1. That means that this div needs to be in the div with the id "column1" and in the first position. I'm not very good with jQuery and javascript so I'm not sure how to go about this. Any help is greatly appreciated!
UPDATE: This is how I update the widget information..
jQuery
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
$.ajax({
url: "/Handlers/SaveWidgets.ashx",
type: "POST",
contentType: "application/json; charset=uft-8",
dataType: "json",
data: JSON.stringify(sortorder),
success: function (response) {
$("#console").html('<div class="success">Dashboard Saved</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
},
error: function (error) {
$("#console").html('<div class="fail">Dashboard was not saved!</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
}
});
AND my Handler..
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
string userId;
public void ProcessRequest(HttpContext context)
{
string userName = context.User.Identity.Name;
conn.Open();
using (SqlCommand cmdUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdUserId.Parameters.AddWithValue("#UserName", userName);
userId = Convert.ToString(cmdUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(userId);
}
String json = String.Empty;
// you have sent JSON to the server
// read it into a string via the input stream
using (StreamReader rd = new StreamReader(context.Request.InputStream))
{
json = rd.ReadToEnd();
}
// create an instance of YourDataModel from the
// json sent to this handler
SaveWidgetsDAL data = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SaveWidgetsDAL));
using (MemoryStream ms = new MemoryStream())
{
byte[] utf8Bytes = Encoding.UTF8.GetBytes(json);
ms.Write(utf8Bytes, 0, utf8Bytes.Length);
ms.Position = 0;
data = serializer.ReadObject(ms) as SaveWidgetsDAL;
}
// update the DB and
// send back a JSON response
int rowsUpdated = 0;
foreach (var item in data.wdata)
{
string itemTitle = item.Title.Replace("FeaturedContent_", "");
string itemColumn = item.ColumnId.Replace("FeaturedContent_column", "");
using (SqlCommand cmd = new SqlCommand("UPDATE tWidgets SET Title = #Title, SortNo = #SortNo, ColumnId = #ColumnId, Collapsed = #Collapsed "
+ "WHERE UserId = #UserId AND Title = #Title;", conn))
{
cmd.Parameters.AddWithValue("#ColumnId", itemColumn);
cmd.Parameters.AddWithValue("#Title", itemTitle);
cmd.Parameters.AddWithValue("#SortNo", item.SortNo);
cmd.Parameters.AddWithValue("#Collapsed", item.Collapsed);
cmd.Parameters.AddWithValue("#UserId", userId);
rowsUpdated = cmd.ExecuteNonQuery();
}
}
conn.Close();
context.Response.ContentType = "application/json";
context.Response.Write("{ \"rows_updated\": " + rowsUpdated + " }");
}
public bool IsReusable
{
get
{
return false;
}
}
UPDATE 2:
With the solution below, I couldn't get it to work. Then I realized when I was updating the widget information, I had to remove FeaturedContent_column and FeaturedContent_ from the column and titles. So I figured I need to put them back in!
for (var i = 0; i < te.d.length; i++) {
$('#FeaturedContent_column' + te.d[i].ColumnId).append($('#FeaturedContent_' + te.d[i].Title));
if (te.d[i].Collapsed) {
//collapse
$('#' + te.d[i].Title).children('.dragbox-content').css('display') == "none";
}
}
This should do it:
for (var i = 0; i < te.d.length; i++) {
$('#column'+te.d[i].ColumnId).append($('#'+te.d[i].Title));
if (te.d[i].Collapsed)
{
//collapse
$('#'+te.d[i].Title).children(".dragbox-content').css('display') = "none";
}
}
This selects the correct column and appends the widget to it based upon the sorting of the array.
$('#column'+te.d[i].ColumnId): The generic $ function of jQuery allows us to select elements in the DOM through a wide range of selectors. Since your widgets have ids we use the id selector #. In this case we append the index to the string column to build the correct column selector.
Once the correct column is selected we're appending the widget to it by using .append and providing the element selected by $('#'+te.d[i].Title). This removes the element from its previous location and adds it to this column (div).
I have Implemented the Search on gridview for columns from this
link. I implemented as per my requirement.But it is not working for me. Please see the code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" class="hoverTable" AutoGenerateColumns="false" AllowPaging="True" BackColor="#E5E5E5" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" ForeColor="Black" GridLines="Vertical" ShowFooter="true" PageSize="5" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating" OnRowDeleting="grdCSRPageData_RowDeleting" OnRowCommand="grdCSRPageData_RowCommand" OnDataBound="grdCSRPageData_DataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:CheckBoxField DataField="Active" HeaderText="Active" ItemStyle-Width="15" />
<asp:TemplateField HeaderText="Edit/Delete" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />
<span onclick="return confirm('Are you sure want to delete?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete"></asp:LinkButton>
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<HeaderTemplate>
<asp:Button ID="btnInsertRecord" runat="server" Text="Add" CommandName="Insert" />
</HeaderTemplate>
<HeaderStyle Width="15%"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the JS script
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="js/quicksearch.js"></script>
<script type="text/javascript">
$(function () {
$('.form-control').each(function (i) {
$(this).quicksearch("[id*=grdCSRPageData] tr:not(:has(th))", {
'testQuery': function (query, txt, row) {
return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
}
});
});
});
</script>
Also see the code behind for your ref:-
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdCSRPageData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdCSRPageData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdCSRPageData.HeaderRow.Parent.Controls.AddAt(1, row);
}
Changes for the grid
protected void grdUser_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdUser.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdUser.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
if (grdUser.Columns[i].HeaderText != "Action" && grdUser.Columns[i].HeaderText != "" && grdUser.Columns[1].HeaderText != "Select") // && grdUser.Columns[i].HeaderText != "" && grdUser.Columns[i].HeaderText != null && grdUser.Columns[i].HeaderText != "Select")
{
cell.Controls.Add(txtSearch);
}
row.Controls.Add(cell);
}
grdUser.HeaderRow.Parent.Controls.AddAt(1, row);
}
When I add the HeaderText != Select. It stops working for the first column, but it works for the other column
There are a lot of elements with form-control class. So can you change your C# code to be:
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdCSRPageData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdCSRPageData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdCSRPageData.HeaderRow.Parent.Controls.AddAt(1, row);
}
and your JS code to be:
<script type="text/javascript">
$(function () {
$('.HaydaBre').each(function (i) {
$(this).quicksearch("[id*=grdCSRPageData] tr:not(:has(th))", {
'testQuery': function (query, txt, row) {
return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
}
});
});
});
</script>
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>