I am working on creating a nested gridview. I am using an example from: http://www.aspsnippets.com/Articles/ASPNet-Nested-GridViews-GridView-inside-GridView-with-Expand-and-Collapse-feature.aspx
The problem is the "minus" of the script does not remove the nested gridview. What seems to be happen is the "plus" function seems to trigger again and again.
<script type = "text/javascript">
$(document).ready(function () {
$("[src*=plus]").on("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$("[src*=minus]").on("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
});
I am using an UpdatePanel (The 2 gridviews are Inside).
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
<asp:GridView ID="GridView1" runat="server" Width = "100%" AutoGenerateColumns = "False" Font-Names = "Arial" CssClass="table table-hover table-bordered"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F18903" HeaderStyle-BackColor = "#F18A07" AllowPaging ="True"
DataKeyNames="Rut" OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer" OnRowDataBound="OnRowDataBound" onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Nombre" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Rut" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Nombre" >
<ItemTemplate>
<asp:Label ID="lblNombre" runat="server" Text='<%# Eval("Nombre")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Rut">
<ItemTemplate >
<asp:Label ID="lblRut" DataField="Rut" runat="server" Text='<%# Eval("Rut")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Fecha de Nacimiento">
<ItemTemplate>
<asp:Label ID="lblFecha_Nac" runat="server" Text='<%# Eval("Fecha_Nac")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div class='input-group date' id='datetimepicker1'>
<asp:TextBox ID="txtFecha_Nac" runat="server" Text='<%# Eval("Fecha_Nac")%>'></asp:TextBox>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Celular">
<ItemTemplate>
<asp:Label ID="lblCelular" runat="server" Text='<%# Eval("Celular")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="txtCelular" runat="server" >
<asp:ListItem Text="SI" Value="1" />
<asp:ListItem Text="NO" Value="0" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField EditText="Editar" ShowEditButton="True" />
<asp:TemplateField HeaderText="Informacion Adicional" >
<ItemTemplate>
<asp:Button ID="Btn1" runat="server"
Text="Ver Mas" CommandArgument="Button1"
OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cambio Final" >
<ItemTemplate>
<asp:Button ID="BtnCambio" runat="server"
Text="Check" CommandArgument="Button1"
OnClick="Btn1_ClickCambioFinal"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#FBEDBB" />
<HeaderStyle BackColor="#F18A07" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
This is an issue with what event is bound when the document is ready.
If you want to "toggle" between two function calls, there are many addon that can help you with that (see this SO question).
An easy way to implement it would be to use jquery one function as mentionned by Tushar Gupta.
function plus() {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
$(this).attr("src", "images/minus.png");
$(this).one("click", minus);
}
function minus() {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
$(this).one("click", plus);
}
$(document).ready(function(){
$("[src*=plus]").one("click", plus);
//You might want to change the selector with a class
// to your img so you don't have to worry about
// opened or closed by default
});
Hope this helps!
Explanations :
The on function bind the event to the DOM element when it is called. In your case, when the document is ready.
When the document is loaded, all your table lines are showing the expand image. Therefore, the "plus click" function is bound to all the img tags.
On the other hand, there are no element showing the minus sign (yet). So no "minus click" function is bound.
The on function doesn't care if you change your element attributes. Remember that your selector selects the elements, even though you filter through the attribute.
In the link you provided, the author used the live function. This function is now deprecated, but it was basically a on function, that would work on the selector now and in the future. This is not the case anymore with the on function.
I would assume that you need to re-subscribe to the events. JavaScript is executed top-down which means that after you have subscribed to the event, elements created later will not trigger that event.
Like the following example:
function myEventHandler () {
// In here you perform your event-specific code
eventSubscription();
}
var eventSubscription = function () {
// Make sure to unsubscribe to prevent event to fire multiple times
$('.myClass').unbind('click');
// Re-subscribe to event
$('.myClass').on('click', myEventHandler);
}
// Call the eventSubscription to hook your events
eventSubscription();
As noMad17 said, you need to re-subscribe to your js methods after a postback, even though you're using an updatePanel. Here is my code:
//js file:
$(document).ready(function () {
loadConfiguration();
});
function loadConfiguration()
{
//add your configuration here
}
//aspx file
<asp:UpdatePanel runat="server" ID="upnl1" UpdateMode="Conditional" >
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(loadConfiguration);
</script>
<!--More code here...-->
</asp:UpdatePanel>
After postback, UpdatePanel is build and all the content inside it as well, so it will load the js code inside add_load again.
Hope it helps
Related
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>
Hi I am developing one application. I have one multiselect dropdownlist box. Whenever i select one value in dropdownlistbox corresponding value in gridview will be having checkbox in below gridview. I want to disable that checkbox. I am basically mvc developer and finding hard times to fix this. I am trying my level best to fix this. For example, whever i select some value in dropdown I am getting ID using jquery as below.
<script>
$(function() {
$('.limitedNumbSelect2').change(function (e) {
var selected = $(e.target).val();
});
});
This is my gridview.
<asp:GridView ID="gdvRegretletter" CssClass="tableform" runat="server" AutoGenerateColumns="False" DataKeyNames="Vendor_ID"
EmptyDataText="No records found !" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvRegretletter_PageIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="true" HeaderText="Select All">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" Text="Check All" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" />
<asp:HiddenField ID="id" runat="server" Value='<%#Eval("Vendor_ID")%>' />
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle VerticalAlign="Top" Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Whenecer i select some value from multiselect dropdownlist box I get id in a variable selected. As soon as I get ID in a variable selected i want to disable that checkbox in gridview. May i have some suggestions on this! Thank you all
Furthur i tried as below.
This is jquery code to hide checkbox
$('.limitedNumbSelect2').change(function (e) {
selected = $(e.target).val();
`$(".disablechk[Text='selected']").prop("disabled", true);`
This is my checkbox code inside gridview.
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" Text='<%#Eval("Vendor_ID")%>' class="disablechk"/>
I am trying to do whenever i get some value from dropdown slected i want to disable that particular checkbox.
If you are getting comma separated string then split it and make an array
var temp = new Array();
temp = selected.split(",");
then loop through it
$.each(temp, function( index, value ) {
$(".disablechk[Text='" + value + "']").prop("disabled", true);
});
You can loop the GridView HiddenField values and disable the checkbox accordingly.
<script type="text/javascript">
$(function() {
$('.limitedNumbSelect2').change(function (e) {
checkGridView($(e.target).val());
});
});
function checkGridView(selected) {
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).val() == selected) {
var checkbox = $(this).prev();
checkbox.prop("disabled", true);
}
});
}
</script>
I'm working on an existing project, doing some updates and have troubles setting the value of "FenSelectedValue" in the "FenDropDownListRoles" Control.
I keep getting the error:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control in repeater control
But the eval in the Label control works fine. I've been reading here and there, and I read things about it not being bound at the right time so I moved the control from "EditItemTemplate" where it eventually should be to "ItemTemplate", to test it, but still no luck..
<ItemTemplate>
<asp:Label ID="lblRolOmschrijving" Text='<%# Eval("Rol_omschrijving") %>' runat="server" />
<fen:FenDropDownListRoles ID="ddlRoles" FenSelectedValue='<%# Eval("Rol_omschrijving") %>' runat="server" Watermark="AdministratorType" Required="true" ValidationGroup="grpAddUser" />
</ItemTemplate>
Here's how I've learned to set drop down selected items in a grid view.
Example grid:
<div id="gridContainerFormulations">
<script type="text/javascript">
$(document).ready(function () {
//This is done here, instead of codebehind, because the SelectedValue property of the drop down list
//simply does not work when databinding. I set the two 'hid' values via the RowEditing event
$("[id$='drpLotNumber']").val($("#hidSelectedFormulationLotNo").val());
});
</script>
<asp:hiddenfield runat="server" id="hidSelectedFormulationLotNo" value="-1" />
<asp:gridview id="dgrStudyFormulations" cssclass="data" runat="server" allowpaging="False" autogeneratecolumns="False"
datakeynames="Id, FormulationLotNo, FormulationNo">
<Columns>
<asp:BoundField HeaderText="Formulation" ReadOnly="True" DataField="FormulationName" />
<asp:TemplateField HeaderText="Lot #">
<EditItemTemplate>
<asp:dropdownlist ID="drpLotNumber" AddBlank="False" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLotNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FormulationLot.Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AI in Formulation" ReadOnly="True" DataField="ActiveIngredientName" />
<asp:TemplateField HeaderText="AI Of Interest">
<EditItemTemplate>
<asp:CheckBox ID="chkOfInterest" Checked='<%# DataBinder.Eval(Container.DataItem, "OfInterest")%>' runat="server" />
</EditItemTemplate>
<ItemTemplate>
<%--<asp:Label ID="lblOfInterest" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "OfInterest")%>' />--%>
<asp:image runat="server" id="imgOfInterest" Visible="False" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AI Amount" ReadOnly="True" DataField="AIAmountText" />
<asp:CommandField ShowEditButton="True" ShowCancelButton="True" ShowDeleteButton="True"/>
</Columns>
</asp:gridview>
Then in row_editing event of grid:
SelectedFormulationLotNo = CType(dgrStudyFormulations.DataKeys(e.NewEditIndex)("FormulationLotNo"), String)
Which sets the hidden field in the HTML
Property SelectedFormulationLotNo() As String
Get
Return hidSelectedFormulationLotNo.Value.Trim()
End Get
Set(value As String)
If String.IsNullOrEmpty(value) Then
hidSelectedFormulationLotNo.Value = String.Empty
Else
hidSelectedFormulationLotNo.Value = value.Trim()
End If
End Set
End Property
And then the jQuery function call sets the correct option in the newly editable row in the grid.
How I finally did it(but leaving the answer on Rake36's answer, since it probably works too and got me in the direction I needed) Since I couldn't get the Javascript to work for some reason and I knew from messing around that I could get the value of labels in "RowDataBound" I combined the method of Rake36 with the hidden field and set the value in the codebehind (in RowDataBound)
In the codebehind:
protected void gvwUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList DropDownListRol = (DropDownList)e.Row.FindControl("ddlRolOmschrijving");
if (e.Row.RowType == DataControlRowType.DataRow && DropDownListRol != null)
{
DsFenVlaanderen.tb_rolDataTable dtRole = DsFenVlaanderen.RolTableAdapter.GetData();
//Fill Dropdownlist
DropDownListRol.DataSource = dtRole;
DropDownListRol.DataValueField = dtRole.Rol_IDColumn.ColumnName;
DropDownListRol.DataTextField = dtRole.Rol_omschrijvingColumn.ColumnName;
DropDownListRol.DataBind();
//Set Selected value
DropDownListRol.Items.FindByValue(hidSelectedRole.Value).Selected = true;
}
}
protected void gvwUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set hiddenfield to value of Rol_ID
hidSelectedRole.Value = gvwUsers.DataKeys[e.NewEditIndex].Values["Rol_ID"].ToString();
}
This is my grid:
<asp:hiddenfield runat="server" id="hidSelectedRole" value="-1" />
<fen:FenGridViewSelectable ID="gvwUsers" runat="server" Selectable="False"
DataSourceID="dsUsers" EnableModelValidation="True" SkinID="Blue"
AllowSorting="True" OnDataBound="gvwUsers_DataBound" OnRowDeleting="gvwUsers_RowDeleting"
AutoGenerateColumns="False" DataKeyNames="User_ID,Rol_ID" OnRowDataBound="gvwUsers_RowDataBound" OnRowEditing="gvwUsers_RowEditing" OnRowUpdating="gvwUsers_RowUpdating">
<Columns>
<asp:BoundField DataField="User_ID" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="User_ID" />
<asp:BoundField DataField="User_ID_EXT" HeaderText="Naam" ReadOnly="true" SortExpression="User_ID_EXT" />
<%-- <asp:BoundField DataField="Rol_omschrijving" HeaderText="Type bestuurder" SortExpression="Rol_omschrijving" /> --%>
<asp:TemplateField HeaderText="Type bestuurder" SortExpression="Rol_omschrijving">
<ItemTemplate>
<asp:Label ID="lblRolOmschrijving" Text='<%# Eval("Rol_omschrijving") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlRolOmschrijving" runat="server" DataField="Rol_omschrijving"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<fen:FenTemplateField HeaderStyle-Width="100px">
<ItemTemplate>
<fen:FenButton ID="btnEdit" runat="server" Function="Edit" />
<fen:FenButton ID="btnDelete" runat="server" Function="Delete" />
</ItemTemplate>
<EditItemTemplate>
<fen:FenButton ID="btnUpdate" runat="server" Function="Update" />
<fen:FenButton ID="btnCancel" runat="server" Function="CancelInline" />
</EditItemTemplate>
</fen:FenTemplateField>
</Columns>
</fen:FenGridViewSelectable>
<asp:ObjectDataSource ID="dsUsers" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="FenVlaanderen.DsFenVlaanderenTableAdapters.vUsersTableAdapter"></asp:ObjectDataSource>
<asp:Label ID="lblNoResults" runat="server" Visible="false" CssClass="error">Er werden geen gebruikers gevonden.</asp:Label>
<asp:Label ID="lblDeleteNotAllowed" runat="server" Visible="false" CssClass="error" />
<fen:AddUser ID="addUser" runat="server" OnFenControlSaved="addUser_FenControlSaved" />
</ContentTemplate>
So I have a new requirement that is tricky to me and I'm unable to figure out so far. I am using a gridview to insert, and update data. One of the requirements that I have is when a user manually adds a new record, if the same "deal number" exists then display a pop up. This pop up should show the record that already exists. They should be able to click 1 of 3 buttons which are "use", "discard", or "Ok". The "use" button will basically close the pop up and clear the textboxes the user was entering in. The "discard" button must delete the record that exists so the user can insert the new record using that same deal number. The reason for this is because the deal number is the most unique number for the "deals" that occur. With the way we are exporting from an old application to a new one, duplicates are downloaded, sometimes some with more information than the first time it was exported. This is why I must add a requirement for the user to choose which record for them to keep. I hope this makes sense to you all. I have dried a few things, but this is what I currently have and I'm stuck on.
The Jquery Script:
<script type="text/javascript">
$(document).ready(function () {
function showpopup() {
$("#popup").dialog("open");
}
$("#popup").dialog({
modal: true,
width: 450,
autoOpen: false,
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
$("#popup").each(function () {
var popup = $(this);
popup.parent().appendTo($("form:first"));
});
});
</script>
And now the division the script calls which has another gridview to display the existing record..
<div class="popUpStyle" title="Duplicate Deal Found!" id="popup" style="display:none">
<asp:GridView ID="gvDealTracking" runat="server" Width="200px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Stock #">
<ItemTemplate>
<asp:Label ID="lblDupStockNumber" runat="server" Text='<%# Bind("StockNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deal #">
<ItemTemplate>
<asp:Label ID="lblDupDealNumber" runat="server" Text='<%# Bind("FIMAST") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DealDate">
<ItemTemplate>
<asp:Label ID="lblDupDealDate" runat="server" Text='<%# Bind("DealDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buyer">
<ItemTemplate>
<asp:Label ID="lblDupBuyer" runat="server" Text='<%# Bind("Buyer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrossProfit">
<ItemTemplate>
<asp:Label ID="lblDupGrossProfit" runat="server" Text='<%# Bind("GrossProfit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AmtFinanced">
<ItemTemplate>
<asp:Label ID="lblDupAmtFinanced" runat="server" Text='<%# Bind("AmtFinanced") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BankName">
<ItemTemplate>
<asp:Label ID="lblDupBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUse" Text="Use" runat="server"></asp:Button>
<asp:Button ID="btnDiscard" Text="Discard" runat="server" OnClick="btnDiscard_Click" style="display:none"></asp:Button>
<asp:Label ID="lblMessagePop" runat="server"></asp:Label>
<br />
</div>
And now the code behind that I use to try to delete the existing record..
protected void btnDiscard_Click(object sender, EventArgs e)
{
try
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
string dealnumber = ((Label)gvr.FindControl("lblDupDealNumber")).Text.Trim();
conn.Open();
SqlCommand cmdDeleteDup = new SqlCommand("DELETE * FROM Vehicle WHERE FIMAST = #FIMAST", conn);
cmdDeleteDup.Parameters.AddWithValue("#FIMAST", dealnumber);
cmdDeleteDup.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
lblMessagePop.Text = ex.ToString();
}
}
The button click isn't not firing and I do now know how to make it work. I tried a few different things but same results. I'm using a reader that checks to see if the record does exists and I show this pop up if it does have rows. It displays perfectly, just my buttons don't do anything. If this isn't the proper way to go about this, please let me know. Any guidance is greatly appreciated!
This is how I'm calling the popup in c#. This has reader that checks to see if the rows exist, and if so, it displays the existing record in the popup. I use a data adapter to do this. Then I use Page.ClientScript... to open the popup and display the results.
SqlDataReader rdr = null;
SqlCommand cmdCheckExisting = new SqlCommand("SELECT StockNumber, DealDate, Buyer FROM Vehicle WHERE FIMAST = '" + DealNumber + "';", conn);
rdr = cmdCheckExisting.ExecuteReader();
if (rdr.HasRows)
{
rdr.Close();
DataTable dt = new DataTable();
SqlDataAdapter cmdReturnExisting = new SqlDataAdapter("SELECT StockNumber, FIMAST, DealDate, Buyer, GrossProfit, AmtFinanced, BankName FROM Vehicle WHERE FIMAST = '" + DealNumber + "';", conn);
cmdReturnExisting.Fill(dt);
gvDealTracking.DataSource = dt;
gvDealTracking.DataBind();
conn.Close();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "showpopup();", true);
}
EDIT: Try removing "style='display:none'" from your div and add "autoOpen: false" into the dialog. Then the only thing your "showpopup()" function needs to do is call "$("#popup").dialog('open');"
$(document).ready(function() {
$("#popup").dialog({
modal: true,
width: 450,
autoOpen: false,
open: function(type,data) {
$(this).parent().appendTo("form");
}
});
$("#popup").each(function() {
var popup = $(this);
popup.parent().appendTo($("form:first"));
});
function showpopup() {
$("#popup").dialog("open");
}
});
I found a solution. I simply changed the buttons to LinkButtons. For some reason, everything works perfectly if asp linkbutton is placed outside or inside the gridview. Here is the popup with the gridview.
<script type="text/javascript">
function showpopup() {
$("#popup").dialog({
modal: true,
width: 590,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
};
</script>
<div class="popUpStyle" title="Duplicate Deal Found!" id="popup" style="display:none">
<asp:GridView ID="gvDealTracking" runat="server" Width="200px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Stock #" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="lblDupStockNumber" runat="server" Text='<%# Bind("StockNumber") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dealership" SortExpression="Dealership">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Dealership") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Dealership") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deal #" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="lblDupDealNumber" runat="server" Text='<%# Bind("FIMAST") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="DealDate">
<ItemTemplate>
<asp:Label ID="lblDupDealDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "DealDate","{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buyer">
<ItemTemplate>
<asp:Label ID="lblDupBuyer" runat="server" Text='<%# Bind("Buyer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrossProfit">
<ItemTemplate>
<asp:Label ID="lblDupGrossProfit" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "GrossProfit","{0:n2}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AmtFinanced">
<ItemTemplate>
<asp:Label ID="lblDupAmtFinanced" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "AmtFinanced","{0:C}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="BankName">
<ItemTemplate>
<asp:Label ID="lblDupBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUse" runat="server" CausesValidation="false" OnClick="btnUse_Click" UseSubmitBehavior="false" Text="Use"></asp:Button>
<asp:Button ID="lbDelete" runat="server" UseSubmitBehavior="false" CausesValidation="False" OnClick="lbDelete_Click" Text="Delete"></asp:Button>
<asp:Label ID="lblMessagePop" runat="server"></asp:Label>
<br />
</div>
EDIT: Thanks to Chad, he pointed out that asp buttons default to use the submit behavior. Setting the UseSubmitBehavior option to false within the button solves the issue. You are now able to use asp buttons within the popup to call your c# methods.
I have an issue with having a asp.net Grid View loaded into a div tag on a page (UI/Host.aspx). The Grid View itself is on a seperate page (GridViews/GridView1.aspx) and I'm using the jQuery load() function to load this page into the div tag.
My problem is when sorting the grid view it tries to postback to the page that's hosting it, and comes back with the error "Unable to find page UI/GridView1.aspx", is there a way to override this so that it post backs to itself, (which I assumed it would but doesn't) or is there an easier way to do the sorting.
Is there any other way of doing this, even if it means getting rid of the GridView altogether and using a repeater and table?
Below is the code:
UI/Hosts.aspx
//jQuery to load the div with the page UI/Hosts.aspx
$(document).ready(function() {
StartRefresh();
});
function startRefresh()
{
refreshID = setInterval(function() {
DisplayDate();
$("#divDests").load("../GridViews/Gridview1.aspx?ConfigID=" + $("#ctl00_MainContent_dlConfiguration").val() + "&ModuleID=" + $("#ctl00_MainContent_ddlModule").val());
}, $("#ctl00_MainContent_ddlRefresh :selected").val());
}
GridViews/Gridview1.aspx;
//Markup for GridViews/Gridview1.aspx
<html>
<head><title></title></head>
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<br />
<asp:GridView Font-Size="8.7pt" ID="gvLiveDest" runat="server" AutoGenerateColumns="False"
EmptyDataText="No Records Found" AllowSorting="true"
onsorting="gvLiveDest_Sorting" onrowcreated="gvLiveDest_RowCreated" OnRowDataBound="gvLiveDest_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="DestinationName" HeaderStyle-CssClass="centralalignment">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("Description")) %>' ToolTip='<%# WebHelper.HTMLSafe(Eval("Description")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Logged <br /> In" HeaderStyle-CssClass="centralalignment" SortExpression="LoggedIn" >
<ItemStyle CssClass="centralalignment" />
<ItemTemplate>
<asp:Label ID="lblLoggedIn" runat="server" Text='<%# SetLoggedIn(Convert.ToBoolean(Eval("Active"))) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current<br />Status" HeaderStyle-CssClass="centralalignment" SortExpression="LastStatus" >
<ItemStyle CssClass="centralalignment" />
<ItemTemplate>
<asp:Label ID="lblCurrentStatus" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("LastStatus")) %>' ToolTip='<%#Eval("LastStatus") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time in<br />Current<br />Status" HeaderStyle-CssClass="centralalignment" SortExpression="CurrentDuration">
<ItemStyle CssClass="RightAlignment" />
<ItemTemplate>
<asp:Label ID="lblCurrentTime" runat="server" Text='<%# ICT.DAL.Reporting.CallDurFormat(Eval("CurrentDuration")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Lines" HeaderText="Lines" HeaderStyle-CssClass="centralalignment" SortExpression="Lines"
ItemStyle-CssClass="centralalignment" />
<asp:BoundField DataField="LinesBusy" HeaderText="Lines <br /> Busy" HeaderStyle-CssClass="centralalignment"
ItemStyle-CssClass="centralalignment" ReadOnly="True" HtmlEncode="False" SortExpression="LinesBusy" />
<asp:BoundField DataField="LinesAvailable" HeaderStyle-CssClass="centralalignment"
ItemStyle-CssClass="centralalignment" SortExpression="LinesAvailable"
HeaderText="Lines <br /> Available" HtmlEncode="false" ReadOnly="True" />
<asp:TemplateField HeaderText="Last Call Time" SortExpression="Timestamp" HeaderStyle-CssClass="centralalignment">
<ItemTemplate>
<asp:Label ID="lblLastCallTime" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("LastCallTime")) %>' ToolTip='<%# WebHelper.HTMLSafe(Eval("LastCallTime")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
And the onSort Event Code (However it never hits this)
protected void gvLiveDest_Sorting(object sender, GridViewSortEventArgs e)
{
if (string.Compare(e.SortExpression, ViewState["SortField"].ToString(), true) == 0)
{
_sortDir = (_sortDir == "ASC") ? "DESC" : "ASC";
}
else
_sortDir = "ASC";
_SortField = e.SortExpression;
ViewState["SortField"] = e.SortExpression;
ViewState["sortDir"] = _sortDir;
BindLiveDestination();
}
I switched over to client-side paging/sorting a while ago and haven't been happier. Of course, you would need to set AllowSorting="false" and AllowPaging="false" in your GridView.
You could put it into an iframe...