How to Add datepicker in asp.net Gridview control - c#

I am trying to add datepicker into a Asp.net Gridview control with column name (cheque_date), when i hardcode the id of Gridview column of a particular row it works fine but for only for that row, but i want to add datepicker for each and every row of Gridview. Below is my Html and jquery code that dose not work as expected. can anyone explain and solve my problem. Thanks in advance
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="loading" style="display: none"></div>
<div class="table-responsive">
<asp:GridView ID="gvBankPayment" CssClass="table table-bordered table-hover dataTable" runat="server" ShowHeaderWhenEmpty="true" ShowFooter="true" AutoGenerateColumns="False" OnRowEditing="gvBankPayment_RowEditing" OnRowDataBound="gvBankPayment_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Chart of Account">
<ItemTemplate>
<asp:DropDownList ID="coa_id" CssClass="form-control" AppendDataBoundItems="true" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RFVCOA" ControlToValidate="coa_id" ForeColor="Red" runat="server" Display="Dynamic" ErrorMessage="Select COA"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="remarks" CssClass="form-control" Text='<%#Eval("remarks")%>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cheque Date">
<ItemTemplate>
<asp:TextBox ID="cheque_date" AutoPostBack="false" CssClass="form-control myDatePickerClass" placeholder="Cheque Date" Text='<%#Eval("cheque_date") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cheque No">
<ItemTemplate>
<asp:TextBox ID="cheque_no" CssClass="form-control" Text='<%#Eval("cheque_no") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="amount" CssClass="form-control" Text='<%#Eval("amount") %>' runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVAmount" ControlToValidate="amount" ForeColor="Red" runat="server" ErrorMessage="Enter Amount"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tax Type">
<ItemTemplate>
<asp:DropDownList ID="tax_id" CssClass="form-control" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WHT(%)">
<ItemTemplate>
<asp:TextBox ID="wht_tax_percent" CssClass="form-control calculateWhtAmount" Text='<%#Eval("wht_tax_percent") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WHT Amount">
<ItemTemplate>
<asp:TextBox ID="wht_tax_amount" CssClass="form-control" Text='<%#Eval("wht_tax_amount") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Amount">
<ItemTemplate>
<asp:TextBox ID="total_amount" CssClass="form-control tamount" Text='<%#Eval("total_amount") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="deleteButton" CssClass="mydelete" runat="server" ImageUrl="~/img/x.png" OnClick="deleteButton_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="ButtonAdd" CssClass="" ImageUrl="~/img/plus-sign-button.png" runat="server" OnClick="ButtonAdd_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No Record Available</EmptyDataTemplate>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
My jquery code is below:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$("#ContentPlaceHolder1_gvBankPayment").on('click', '.myDatePickerClass', function () {
var currentRow = $(this).closest("tr");
var input = ('#' + currentRow.find("td:eq(2) input").attr('id'));
$(input).datepicker({
dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: '1950:2013', yearRange: '1950:2050'
});
});
});

You should change your script to this. It is also better to make a function and not place it inside the endRequest. Because as your code is now it will not bind the datepicker on first load, but only after a UpdatePanel update.
Note the use of ClientID
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
bindDatePicker();
});
bindDatePicker();
function bindDatePicker() {
$("#<%=gvBankPayment.ClientID %> .myDatePickerClass").focusin(function () {
$(this).datepicker({
dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: '1950:2013', yearRange: '1950:2050'
});
});
}
</script>

Related

Get text box value from grid view Header

I have grid with text box for filter data on header.I have button outside the grid.I am using this gridview for filtering the grid by some columns. When I click on button I want to get value from text box and dropdownlist on codebehind.cs, below is my webform.aspx code of gridview,
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:GridView ID="TrackerGrid" runat="server" BackColor="#CCCCCC" AllowPaging="True" AutoGenerateColumns="false">
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="User ID" SortExpression="User ID">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Eval("User ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<HeaderTemplate>
Full Name:
<asp:DropDownList ID="ddlfullName" runat="server" AutoPostBack="true" OnSelectedIndexChanged="onselectDropdown">
<asp:ListItem Text="ALL" Value="ALL" Selected="True"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("Full Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<HeaderTemplate>
Email Id:
<asp:TextBox ID="txtemail" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<HeaderTemplate>
<asp:Label ID="lbllng" runat="server" Text="Longitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllongi" runat="server" Text='<%# Eval("Longitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lattitude">
<HeaderTemplate>
<asp:Label ID="lbllat" runat="server" Text="Lattitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllatti" runat="server" Text='<%# Eval("Lattitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activated On">
<HeaderTemplate>
<asp:Label ID="lbldevices" runat="server" Text="Activated On"></asp:Label></br>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbldevice" runat="server" Text='<%# Eval("Activated On") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location DateTime" SortExpression="Location DateTime">
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Location DateTime"></asp:Label></br>
<asp:Label ID="lblStartDate" runat="server" AssociatedControlID="txtStartDate" Text="Start Date"></asp:Label>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarStartDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtStartDate" popupbuttonid="imgPopup1"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup1" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</br>
<asp:Label ID="lblEndDate" runat="server" Text="End Date" AssociatedControlID="txtEndDate"></asp:Label>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarEndDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtEndDate" popupbuttonid="imgPopup2"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup2" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDatetime" runat="server" Text='<%# Eval("Location DateTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am getting texbox value in codebehind code.
protected void getTextBoxValue(object sender, EventArgs e)
{
DropDownList ddlfullname = (TrackerGrid.HeaderRow.FindControl("ddlfullName") as DropDownList);
string selectedValue = ddlfullname.SelectedItem.Text;
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = mobilenumber.Text;
TextBox email = TrackerGrid.HeaderRow.FindControl("txtemail") as TextBox;
string emailid = email.Text;
TextBox staloc = TrackerGrid.HeaderRow.FindControl("txtStartDate") as TextBox;
string startlocatdate = staloc.Text;
TextBox endloc = TrackerGrid.HeaderRow.FindControl("txtEndDate") as TextBox;
string endlocadate = endloc.Text;
}
I am getting empty value when I debugging this code.I think my code is correct but how i am not getting value of textboxes, i don't understand. Please help me for solving my issue.
Thanks in advance.
You probably did not wrap the DataBind() of the Gridview inside an IspostBack check. If you do not then the values will be rested by the DataBind instead of being saved with ViewState.
protected void Page_Load(object sender, EventArgs e)
{
//not here
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
if (IsPostBack == false)
{
//but inside an ispostback check
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
}
}

How to maintain scroll position of a page when add dynamic rows in GridView?

In my web page, I have an LinkButton inside FooterTemplate, when I Add new row in GridView by using RowCommand. LinkButton do partial postback but my page loses its current scroll position and return scroll to top of the page. How should I maintain my page scroll position when I add new Item in my GridView.
Below is my screen output:
Below is my page code:
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Invoice.aspx.cs" Inherits="RSMS.Users.Invoice" %>
<asp:UpdatePanel ID="upItemDetail" runat="server">
<ContentTemplate>
<asp:GridView
ID="gvItemDetail"
runat="server"
Width="100%"
ShowHeaderWhenEmpty="true"
AutoGenerateColumns="false"
EmptyDataText="No Data Found!"
ShowFooter="False"
BorderStyle="None"
CellPadding="3"
GridLines="Horizontal"
SkinID="AHGridView"
OnRowCommand="gvItemDetail_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Item ID">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
TabIndex="5"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sales Price">
<ItemTemplate>
<asp:Label ID="lblItemSalesPrice" runat="server" Text='<%# Eval("Sale_Price") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvPrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
Text='<%# Eval("Sale_Price") == null ? "0" : Eval("Sale_Price") %>'
TabIndex="6"
ClientIDMode="Static"
CssClass="form-control"></asp:TextBox>
<asp:HiddenField ID="hdnPurchase_Price" runat="server" ClientIDMode="Static" Value="0" />
<%--<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>--%>
<%--<asp:RequiredFieldValidator
ID="rfvPurchasePrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item QTY">
<ItemTemplate>
<asp:Label ID="lblItemQTY" runat="server" Text='<%# Eval("Item_Qty") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
Text='<%# Eval("Item_Qty") == null ? "0" : Eval("Item_Qty") %>'
TabIndex="7"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UOM">
<ItemTemplate>
<asp:Label ID="lblUOM" runat="server" Text='<%# Eval("Item_UOM") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
CssClass="ah-border-less"
AutoPostBack="true">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="1">GM</asp:ListItem>
<asp:ListItem Value="2">KG</asp:ListItem>
<asp:ListItem Value="3">PCS</asp:ListItem>
<asp:ListItem Value="4">DZ</asp:ListItem>
<asp:ListItem Value="5">BOX</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
TabIndex="8"
CssClass="ah-border-less">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="GM">GM</asp:ListItem>
<asp:ListItem Value="KG">KG</asp:ListItem>
<asp:ListItem Value="PCS">PCS</asp:ListItem>
<asp:ListItem Value="DZ">DZ</asp:ListItem>
<asp:ListItem Value="BOX">BOX</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price">
<ItemTemplate>
<asp:Label ID="lblTotalPrice" Text='<%# Eval("Total_Price") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text='<%# Eval("Total_Price") == null ? "0" : Eval("Total_Price") %>'></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="itemAdd" ClientIDMode="AutoID" CommandName="Add" runat="server" TabIndex="9">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
Aspx.cs Code:
protected void gvItemDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
HiddenField itemID = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnItemID");
HiddenField itemPurchasePrice = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnPurchase_Price");
TextBox itemName = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemName");
TextBox itemSalesPrice = (TextBox)gvItemDetail.FooterRow.FindControl("txtSalesPrice");
TextBox itemQTY = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemQuantity");
DropDownList itemUOM = (DropDownList)gvItemDetail.FooterRow.FindControl("ddlUOM");
Label itemTotalPrice = (Label)gvItemDetail.FooterRow.FindControl("lblTotalPrice");
Decimal dcmTotalPrice = (Convert.ToDecimal(itemSalesPrice.Text.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
Decimal dcmPurchasePrice = (Convert.ToDecimal(itemPurchasePrice.Value.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
DataTable dt = (DataTable)HttpContext.Current.Session["dtInvoiceItemDetail"];
//dt.Rows[0].Delete();
dt.Rows.Add(itemID.Value.Trim(),
itemName.Text.Trim(),
itemSalesPrice.Text.Trim(),
itemQTY.Text.Trim(),
itemUOM.SelectedValue.ToString().Trim(),
dcmTotalPrice,
dcmPurchasePrice
);
dt.AcceptChanges();
gvItemDetail.DataSource = dt;
gvItemDetail.DataBind();
gvItemDetail.Rows[0].Visible = false;
HttpContext.Current.Session["dtInvoiceItemDetail"] = dt;
lblCalculateTotal.Text = (Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Total_Price"])))).ToString();
commission = ((Convert.ToDecimal(lblCalculateTotal.Text.Trim()) - Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Purchase_Price"])))) * 10) / 100;
}
gvItemDetail.FooterRow.Focus();
}
What I've tried:
Maintain Panel Scroll Position On Partial Postback ASP.NET
Re: Update Panel Scrolling Issue
Maintain Panel Scroll Position On Postback in ASP.NET
page jumps to top
how to retain browser scroll position for Dynamic Control Events
I've found my solution that when I remove gvItemDetail.FooterRow.Focus(); code my page maintain its scroll position. Thanks for all of your comments.
I face this issue before. My resolution is to add maintainScrollPositionOnPostBack="true" in the web.config file
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<pages maintainScrollPositionOnPostBack="true" /> //this will keep current position after postback
</system.web>

Copy value from one textbox to another with jQuery in multiple gridview rows

I have a grid view that the user can add 1 or more rows to at a time. I need to copy the begin date to the end date textbox if the end date textbox is empty. I have this working if the grid was empty when the rows are added, but I can't figure out how to do this when later adding rows to the grid.
This is because I may only have two rows with textboxes so the array of them only has 2 entries, but my row index might indicate this is the 6th row. I can't figure out how to determine what textbox is being used so I can copy to the end date textbox in the same row.
GridView
<asp:GridView ID="gvOfferingDates" runat="server"
AutoGenerateColumns="False"
onrowdatabound="gvOfferingDates_RowDataBound"
onrowediting="gvOfferingDates_RowEditing"
onrowcancelingedit="gvOfferingDates_RowCancelingEdit"
onrowupdated="gvOfferingDates_RowUpdated"
onrowupdating="gvOfferingDates_RowUpdating" Width="100%" >
<Columns>
<asp:TemplateField>
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/Edit.png" Visible='<%# !IsEditable(Eval("NewRow")) %>' />
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Delete.png" Visible='<%# IsEditable(Eval("NewRow")) %>' />
<asp:ImageButton ID="btnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/undo.png" CausesValidation="False" Visible='<%# EditMode %>' />--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Begin Date">
<ItemTemplate>
<asp:Label runat="server" ID="lblBeginDate" Text='<%# Eval("BeginDate", "{0:MM/dd/yyyy}") %>' Visible='<%# !IsEditable(Eval("NewRow")) %>'></asp:Label>
<asp:Label runat="server" ID="lblBeginDateEdit" Text='<%# Eval("BeginDate", "{0:MM/dd/yyyy}") %>' Visible="false"></asp:Label>
<asp:Label ID="lblBeginRequired" runat="server" Text="*" ForeColor="Red" Visible='<%# IsEditable(Eval("NewRow")) %>'></asp:Label>
<asp:TextBox CssClass="begindate" ID="txtBeginDate" runat="server" Visible='<%# IsEditable(Eval("NewRow")) %>' BackColor="#FFFACD"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<asp:Label runat="server" ID="lblEndDate" Text='<%# Eval("EndDate", "{0:MM/dd/yyyy}") %>' Visible='<%# !IsEditable(Eval("NewRow")) %>'></asp:Label>
<asp:Label runat="server" ID="lblEndDateEdit" Text='<%# Eval("EndDate", "{0:MM/dd/yyyy}") %>' Visible="false"></asp:Label>
<asp:Label ID="lblEndRequired" runat="server" Text="*" ForeColor="Red" Visible='<%# IsEditable(Eval("NewRow")) %>'></asp:Label>
<asp:TextBox CssClass="enddate" ID="txtEndDate" runat="server" BackColor="#FFFACD" CausesValidation="True" Visible='<%# IsEditable(Eval("NewRow")) %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
jQuery
$(document).ready(function() {
$(".begindate").datepicker({
onSelect: function(dateText, ui) {
var bDate = $(this).val();
var iRowIndex = $(this).closest("tr").prevAll("tr").length;
var $arrT = $('#<%=gvOfferingDates.ClientID %>').find('input:text[id$="txtEndDate"]');
var txtEnd = $($arrT[iRowIndex - 1]);
if ($($txtEnd).val().length == 0) {
$($txtEnd).val(bDate);
}
},
changeMonth: true, changeYear: true, minDate: new Date()
}).on("change", function() {
$(this).blur()
});
$(".enddate").datepicker({
onSelect: function() {
minDate: new Date($(".begindate"))
},
changeMonth: true, changeYear: true, minDate: new Date($(".begindate"))
});
Update
Changing the jquery to the much simpler below worked for new records and adding to existing ones.
$(".begindate").datepicker({
onSelect: function(dateText, ui) {
var bDate = $(this).val();
var txtEnd = $(this).closest("tr").find('input:text[id$="txtEndDate"]');
if (txtEnd.val().length == 0) {
txtEnd.val(bDate);
}
},
changeMonth: true, changeYear: true, minDate: new Date()
}).on("change", function() {
$(this).blur()
});
If you have the begindate element, you should be able to access the enddate element with the following steps:
Get the closest TR parent element.
Search inside the TR children elements for an input with an enddate id . Both the textboxes should be in the same table row.
I'm not sure, but it would be something like this:
var txtEnd = $(begindateElement).closest("tr").find('input:text[id$="txtEndDate"]');

Problems with nested gridview

I am trying to design gridview inside gridview with insert update and delete but in this i cant insert record. Can anyone Help?
Here is database table
1) tbl_SShow(ShowTimeId{P-Auto inc.},TheatreId,MovieId,FromDate,ToDate)
2) tbl_Show(ShowID{P-Auto inc.},ShowTime,Silver,Gold, Platinum,ShowTimeId)
3) tbl_Theatre(TheatreId{P-Auto inc.}, TName, Taddress)
and here is aspx page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function expandcollapse(obj,row)
{
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);
if (div.style.display == "none")
{
div.style.display = "block";
if (row == 'alt')
{
img.src = "minus.gif";
}
else
{
img.src = "minus.gif";
}
img.alt = "Close to view other Customers";
}
else
{
div.style.display = "none";
if (row == 'alt')
{
img.src = "plus.gif";
}
else
{
img.src = "plus.gif";
}
img.alt = "Expand to show Orders";
}
}
</script>
</head>
<body>
<form id="AddEventForm" runat="server">
<ul id="tabsmenu1" class="tabsmenu">
<li class="active">Add Show Time</li>
</ul>
<div class="form">
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="#f1f1f1"
AutoGenerateColumns=false DataSourceID="SqlDataSource1" DataKeyNames="MovieID"
GridLines=None OnRowDataBound="GridView1_RowDataBound"
OnRowCommand = "GridView1_RowCommand" OnRowUpdating = "GridView1_RowUpdating" BorderStyle=Outset
OnRowDeleting = "GridView1_RowDeleting" OnRowDeleted = "GridView1_RowDeleted"
OnRowUpdated = "GridView1_RowUpdated" AllowSorting=true
Width="80%" >
<RowStyle BackColor="Gainsboro" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#0083C1" ForeColor="White"/>
<FooterStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("ShowTimeId") %>', 'one');">
<img id="imgdiv<%# Eval("ShowTimeId") %>" alt="Click to show/hide Orders for Customer <%# Eval("ShowTimeId") %>" width="9px" border="0" src="../images/plus.gif"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theatre Id" SortExpression="TheatreId">
<ItemTemplate>
<asp:Label ID="lblShowTimeId" Text='<%# Eval("ShowTimeId") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblShowTimeId" Text='<%# Eval("ShowTimeId") %>' runat="server"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theatre Id" SortExpression="TheatreId">
<ItemTemplate>
<asp:Label ID="lblTheatreId" Text='<%# Eval("TheatreId") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTheatreId" Text='<%# Eval("TheatreId") %>' runat="server"></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTheatre" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="1">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie Id" SortExpression="MovieId">
<ItemTemplate><%# Eval("MovieId")%></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlMovie" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="2">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMovie" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="2">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="From Date" SortExpression="FromDate">
<ItemTemplate><%# Eval("FromDate")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFromDate" Text='<%# Eval("FromDate") %>' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtFromDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFromDate" Text='' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtFromDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To Date" SortExpression="ToDate">
<ItemTemplate><%# Eval("ToDate")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtToDate" Text='<%# Eval("ToDate") %>' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="txtToDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton2">
</asp:CalendarExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtToDate" Text='' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="txtToDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton2">
</asp:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteShow" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddShow" CommandName="AddShow" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("ShowTimeId") %>" style="display:none;position:relative;left:15px;OVERFLOW: auto;WIDTH:97%" >
<asp:GridView ID="GridView2" AllowPaging="True" AllowSorting="true" BackColor="White" Width=100% Font-Size=X-Small
AutoGenerateColumns="false" Font-Names="Verdana" DataKeyNames="ShowTimeId" runat="server" ShowFooter="true"
OnPageIndexChanging="GridView2_PageIndexChanging" OnRowUpdating = "GridView2_RowUpdating" CssClass="Gridview"
OnRowCommand = "GridView2_RowCommand" OnRowEditing = "GridView2_RowEditing" GridLines=None
OnRowUpdated = "GridView2_RowUpdated" OnRowCancelingEdit = "GridView2_CancelingEdit" OnRowDataBound = "GridView2_RowDataBound"
OnRowDeleting = "GridView2_RowDeleting" OnRowDeleted = "GridView2_RowDeleted" OnSorting = "GridView2_Sorting"
BorderStyle=Double BorderColor="#0083C1">
<RowStyle BackColor="Gainsboro" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#0083C1" ForeColor="White"/>
<FooterStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Show ID" SortExpression="ShowID">
<ItemTemplate>
<asp:Label ID="lblShowID" Text='<%# Eval("ShowID") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblShowID" Text='<%# Eval("ShowID") %>' runat="server"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShowTime" SortExpression="ShowTime">
<ItemTemplate><%# Eval("ShowTime")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtShowTime" Text='<%# Eval("ShowTime")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtShowTime" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Silver" SortExpression="Silver">
<ItemTemplate><%# Eval("Silver")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtSilver" Text='<%# Eval("Silver")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSilver" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gold" SortExpression="Gold">
<ItemTemplate><%# Eval("Gold")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGold" Text='<%# Eval("Gold")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGold" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Platinum" SortExpression="Platinum">
<ItemTemplate><%# Eval("Platinum")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlatinum" Text='<%# Eval("Platinum")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPlatinum" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteCust" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddOrder" CommandName="AddShow" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Event_MovieConnectionString %>"
SelectCommand="SELECT s.[ShowTimeId], s.[TheatreId], s.[MovieId], s.[FromDate], s.[ToDate], s.[Created],
s.[Modified] FROM [tbl_SShow] s ORDER BY s.[ShowTimeId]">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Please give me a solutions
Thanks.

how to keep the textbox values in asp.net gridview after checking the required field validation

I have a regular gridview with insert,edit,update, delete operations as in below image:
Before inserting data to the DB, I am doing the validation on the textboxes if they are filled or empty like this:
if (txtNewID.Text == "")
{
string message = "Please enter ID";
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Alert", "alert('" + message + "')", true);
isValid = false;
}
But after clicking the OK button of the alert message, the values that i added in the required textboxes are getting lost. How to keep the values of the textboxes in gridview?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code, Type" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<tr>
<td class="style1" >
<asp:GridView ID="gridID" DataKeyNames="Tracker_ID , Current_Status" runat="server"
GridLines="Both" Width="600px" BorderColor="Black"
ShowFooter="true" AutoGenerateColumns="false"
onrowcancelingedit="gridID_RowCancelingEdit"
onrowediting="gridID_RowEditing" onrowcommand="gridID_RowCommand"
onrowdeleting="gridID_RowDeleting" onrowdatabound="gridID_RowDataBound" onrowupdating="gridID_RowUpdating"
>
<Columns>
<asp:TemplateField HeaderStyle-BackColor="#1B7AE0" HeaderStyle-Font-Size="10" HeaderText="ID#">
<EditItemTemplate>
<asp:TextBox ID="ID" BorderWidth="1" Text='<%# Eval("ID") %>' Width="50px" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewID" BorderWidth="1" Width="50px" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblID" Font-Size="Smaller" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#1B7AE0" Font-Size="10pt"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID Description" HeaderStyle-BackColor="#1B7AE0" HeaderStyle-Font-Size="10">
<EditItemTemplate>
<asp:TextBox ID="IDDesc" Text='<%# Eval("ID_Description") %>' Width="99px" BorderWidth="1" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewIDDesc" BorderWidth="1" Width="99px" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblIDDesc" Font-Size="Smaller" Text='<%# Bind("ID_Description") %>' runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#1B7AE0" Font-Size="10pt"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="HCL Author" HeaderStyle-BackColor="#1B7AE0" HeaderStyle-Font-Size="10">
<EditItemTemplate>
<asp:TextBox ID="txtHclAuthor" Text='<%# Eval("HCL_Author") %>' Width="95px" BorderWidth="1" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewHclAuthor" BorderWidth="1" Width="95px" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblHclAuthor" Font-Size="Smaller" Text='<%# Bind("HCL_Author") %>' runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#1B7AE0" Font-Size="10pt"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Xerox Author" HeaderStyle-BackColor="#1B7AE0" HeaderStyle-Font-Size="10">
<EditItemTemplate>
<asp:TextBox ID="txtXeroxAuthor" Text='<%# Eval("Xerox_Author") %>' Width="95px" BorderWidth="1" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewXeroxAuthor" BorderWidth="1" Width="95px" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblXeroxAuthor" Font-Size="Smaller" Text='<%# Bind("Xerox_Author") %>' runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#1B7AE0" Font-Size="10pt"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Track" HeaderStyle-BackColor="#1B7AE0" HeaderStyle-Font-Size="10">
<EditItemTemplate>
<asp:TextBox ID="IDTrack" Text='<%# Eval("Track") %>' Width="80px" BorderWidth="1" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewIDTrack" BorderWidth="1" Width="80px" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblIDTrack" Font-Size="Smaller" Text='<%# Bind("Track") %>' runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#1B7AE0" Font-Size="10pt"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td> </tr> </ContentTemplate>
</asp:UpdatePanel>
Whenever PostBack event is called then we can loss the page data.Did you place the grid in updatepanel otherwise place it in grid if you didn't get maintain the values in viewstate.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx
Bind the validator to the textbox you need to be required before a submit/post is valid using the ControlToValidate property.
Try to find required field validator dynamically on RowDataBoundEvent of Grid View.
TextBox tb=e.Row.FindControl("txtBox") as TextBox;
tb.ValidationGroup=e.RowIndex;
RequiredFieldvalidation rv=e.Row.FindControl("rv") as
RequiredFieldValidator; rv.ControlTovalidate=tb; rv.ErrorMessage;
rv.ErrorMessage="*";
rv.ValidationGroup=e.RowIndex;

Categories