SweetAlert confirmation dialog with asp.net listview delete? - c#

Please help me fathom this.
I have created a ListView, displaying data from a SQL database. I have enabled inserting, editing and deleting and it all works.
What do I want?
I want to use SweetAlert to prompt the user to confirm yes/no whether they want to delete the entry from the ListView or not.
What have I done?
First I tried using the "builtin" functionality where I added OnClientClick="return confirm('are you sure')" to the <asp:Button/> calling the delete of the given ListView entry. That worked! When I clicked yes it deleted and no it didn't. I didn't have to do anything other than add the above. But It is not what I want. I want the fancier SweetAlert to be displayed, and here the problem starts.
Second I thought I could simply create the SweetAlert script and call its function name from the button. However when doing so, it does open SweetAlert but before I even get the chance to click yes and no, it has already deleted the item and closes the box.
<script>
function deletealert()
{
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
</script>
Now I know that there is no functionality in the above, but I didn't even get the chance to move to the yes and no, it closed the script by itself. Then I found out that I could stop the deleting by setting CausesValidation=false on the delete <asp:Button /> but then nothing happened at all.
Third I think I have a breakthrough, but I have no clue how to finish it. I found out that on the ListView, there is an event called ItemDeleting. This event fires before the delete is executed. I tested it out, and it works.
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true); //Calls the sweetalert
e.Cancel = true;
//e.Cancel = false;
}
If I use the e.Cancel = true; then the item is not deleted and the action is cancelled. If I use the e.Cancel = false; then the item is deleted. So I think I may have to incorporate that functionality with the above jQuery. I don't know if I can put jQuery inside the protected void and work with it from there either?
Updated to include suggested solution from haraman Here is also the entire .aspx page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="forum-front.aspx.cs" Inherits="initial.site.forum_front" EnableViewState="true" EnableEventValidation="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="Content/sweetalert.min.js"></script>
<%--CSS Style Sheets--%>
<link href="Content/Styles.css" rel="stylesheet" />
<link href="Content/StylesPanel.css" rel="stylesheet" />
<link href="Content/sweetalert.css" rel="stylesheet" />
<%--Java Scripts--%>
<script>
function deletealert(ctl) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
// RESUME THE DEFAULT LINK ACTION
eval(defaultAction);
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
</script>
<asp:Panel ID="Panel1" runat="server" Height="1401px">
<center>
<table>
<tr>
<td>
<asp:Button ID="TilForsiden" runat="server" OnClick="TilForsiden_Click" Text="Forsiden" CssClass="button" />
</td>
<td>
<asp:Panel ID="Panel2" runat="server" CssClass="panel panel-default">
<h1><asp:Label ID="ForumOverskrift" runat="server" CssClass=""></asp:Label></h1>
</asp:Panel>
</td>
</tr>
</table>
</center>
<center>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" InsertItemPosition="LastItem" DataKeyNames="OpslagsID" OnDataBound="SkrivOpslag_Click">
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton1" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Rediger" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</AlternatingItemTemplate>
<EditItemTemplate>
<tr style="">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="btn-default" />
</td>
<td>
<asp:TextBox ID="IndholdTextBox" runat="server" Text='<%# Bind("Indhold") %>' />
</td>
<td>
<asp:TextBox ID="EmneTextBox" runat="server" Text='<%# Bind("Emne") %>' />
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<InsertItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="EmneTextBox" Placeholder="Emne..." runat="server" Text='<%# Bind("Emne") %>' CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="IndholdTextBox" Placeholder="Skriv her..." runat="server" Text='<%# Bind("Indhold") %>' CssClass="form-control" ToolTip="Skriv dit indhold her" TextMode="MultiLine" Rows="8" Width="500px" />
</td>
</tr>
</table>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Udgiv" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Ryd" CssClass="btn-default" />
</td>
<td></td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton2" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="" class="table table-striped">
<tr runat="server" style="">
<th runat="server"></th>
<th runat="server">Indhold</th>
<th runat="server">BrugerNavn</th>
<th runat="server">Postnummer</th>
<th runat="server">Emne</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Button ID="SkrivOpslag" runat="server" CommandName="SkrivOpslag" Text="Skriv Opslag" CssClass="btn btn-default btn-xs" OnClick="SkrivOpslag_Click" />
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" FirstPageText="Første Side" ShowLastPageButton="True" LastPageText="Sidste Side" PreviousPageText="Forrige" NextPageText="Næste" ButtonCssClass="btn btn-default" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" CssClass="btn btn-default btn-xs" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
</center>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="True" ConnectionString="<%$ ConnectionStrings:foradbConnectionString %>" DeleteCommand="DELETE FROM [testOpslagstabel] WHERE [OpslagsID] = #OpslagsID" InsertCommand="INSERT INTO [testOpslagstabel] ([Indhold], [DatoTid], [Reference], [BrugerNavn], [Emne], [Postnummer]) VALUES (#Indhold, GetDate(), #Reference, 'testuser', #Emne, #Postnummer)"
SelectCommand="SELECT * FROM [testOpslagstabel] WHERE ([Postnummer] = #Postnummer)" UpdateCommand="UPDATE [testOpslagstabel] SET [Indhold] = #Indhold, [DatoTid] = #DatoTid, [Reference] = #Reference, [BrugerNavn] = 'testuser', [Postnummer] = #Postnummer, [Emne] = #Emne WHERE [OpslagsID] = #OpslagsID"
InsertCommandType="Text">
<DeleteParameters>
<asp:Parameter Name="OpslagsID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
<asp:Parameter Name="OpslagsID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Panel>
</asp:Content>
Just to make everything more clear I'm updating the post with the full code in my code behind the aspx. Also if it makes the understanding better, I'm trying to create a forum.
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace initial.site
{
public partial class forum_front : System.Web.UI.Page
{
string qbynavn;
object objbynavn;
// Makes the SQL connection string
String CS = ConfigurationManager.ConnectionStrings["FORADB"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string qpostnr = Request.QueryString["Postnummer"];
if (qpostnr != null)
{
try
{
using (SqlConnection con = new SqlConnection(CS))
{
// specifies the command to check for zipcode
SqlCommand cmd = new SqlCommand("SELECT Bynavn FROM Postnummertabel WHERE Postnr = " + qpostnr, con);
// Opens the connection
con.Open();
objbynavn = cmd.ExecuteScalar();
qbynavn = objbynavn.ToString();
ForumOverskrift.Text = " Velkommen til " + qbynavn;
}
}
catch (Exception ex)
{
Response.Write("Der opstod en fejl! " + ex.Message);
}
}
else
{
ForumOverskrift.Text = " Velkommen!";
}
}
public void AnswerButton_Click(object sender, EventArgs e)
{
// Tries to bind the sender to the right button.
Button originator = sender as Button;
// Checks if it has been found
if (originator != null)
{
// Goes throug the control hierachy to find the right item.
var parentItem = originator.Parent as ListViewItem;
if (parentItem != null
&& parentItem.ItemType == ListViewItemType.DataItem)
{
// Binds the textbox and button to variables
var textBox = parentItem.FindControl("AnswerTextBox") as TextBox;
var btn = parentItem.FindControl("AnswerButton") as Button;
if (textBox != null)
{
// Changes the textbox to being visible and changes the buttons text.
if (textBox.Visible == false)
{
textBox.Visible = true;
btn.Text = "Fortryd";
}
// Changes the textbox to invisible and changes the buttons text.
else if (textBox.Visible == true)
{
textBox.Visible = false;
btn.Text = "Svar";
}
}
}
}
}
// Makes the Skriv Opslag field either visible or invisible
protected void SkrivOpslag_Click(object sender, EventArgs e)
{
if (ListView1.InsertItem.Visible == true)
{
// Makes the Skriv Opslag field invisible
ListView1.InsertItem.Visible = false;
// Changes the buttons name to Skriv Opslag
Button btn = (Button) ListView1.FindControl("SkrivOpslag");
btn.Text = "Skriv Opslag";
}
else if (ListView1.InsertItem.Visible == false)
{
// Makes the Skriv Opslag field visible
ListView1.InsertItem.Visible = true;
// Changes the Buttons name to Skriv Opslag
Button btn = (Button)ListView1.FindControl("SkrivOpslag");
btn.Text = "Fortryd";
}
}
protected void TilForsiden_Click(object serder, EventArgs e)
{
Response.Redirect("~/welcomepage.aspx");
}
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true);
//e.Cancel = true;
//Response.Write("<script>deletealert();</script>");
//ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "deletealert();", true);
}
}
}

First you must understand that you can not mix server side code then client side code and then again server code in one go as you are currently doing in ItemDeleting event. All client side code will fire only when the page PostBacks after completing the server side code execution.
Now, with regard to your use of plugin. Have you returned anything from the swal function?
Lets try to do it the old way using your first method OnClientClick="return confirm('are you sure')". Modify it to OnClientClick="return deletealert();". Now in JavaScript return true/false in your deletealert function (focus on comments in CAPITALS)
... YOUR OTHER CODE IN DELETEALERT
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
//RETURN TRUE TO EXECUTE SERVER CODE
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
//RETURN FALSE TO SKIP SERVER CODE
return false;
}
});
... YOUR OTHER CODE
Update:
The working of SweetAlert is somewhat different from a regular alert. It does shows a modal window but does not prevent any action initiated by the user such as submit, link click. So the workaround is to store the href of the link in a var, show SweetAlert and then use eval to resume that link.
function deletealert(ctl, event) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({ title: "Deleted!", text: "Your imaginary file has been deleted.", type: "success", confirmButtonText: "OK!", closeOnConfirm: false },
function () {
// RESUME THE DEFAULT LINK ACTION
window.location.href = defaultAction;
return true;
});
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
I have replaced the asp:Button with asp:LinkButton just for easy handling of preventDefault and then resuming the operation.
<asp:LinkButton OnClientClick="return deletealert(this, event);" ID="DeleteButton" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
Only one small glitch needs to be tackled is when the user finally clicks the ConfirmButton the final success message is displayed but at the same time the default action is also executed resulting in a postback. Updated to postback after final success message and FireFox update.

You need to prompt before you get to the server; so attach to the delete button click using jQuery:
$("#idofplaceholderwrappingtheitems").find("[id$='DeleteButton']").on("click", function(e) {
//show confirmation here;
});
Showing the javascript in ItemDeleting is too late in the process.

Related

The name 'control' does not exist in the current context

I am having trouble with an error on a site I am working on that I've inherited, upon grabbing the source from the repository and building, then clearing out a few reference errors, I am still getting over 1000 instances of this error:
The name 'pnlDetails' does not exist in the current context (replace 'panelDetails' with any of my control names).
what this would seem to indicate is that the controls referenced server side are not declared on the page, or don't have runat=server in them, but in fact they do. it could also be a problem of the inherits attribute not matching, but it does. I have searched stackoverflow and seen this question before, though after trying some of the solutions mentioned, they did not help. I do not have any designer files for my pages. Below are some snippets of code from the aspx and aspx.cs pages. (some information redacted to protect client privacy)
My question is, why can't i reference my controls on the server side? 'paneldetails', 'rpAddresses' etc.?
default.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/org.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="directory_Default" %>
<%# Register Assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=xxxx"
Namespace="System.Web.UI.WebControls" TagPrefix="asp" %>
<%# Register TagPrefix="nu" Namespace="Leap.NuCaptcha" Assembly="leapmarketing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" Runat="Server">
<title>xxxx</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphBreadCrumb" Runat="Server">
<div id="breadCrumbFrame">Home > xxx</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphBody" Runat="Server">
<h3 class="sectionTitle"> xxx </h3>
<!--//////////// Begin Searchbox Panel ////////////-->
<asp:Panel ID="pnlSearchbox" Visible="true" runat="server" DefaultButton="lnkSearch">
<div class="info">
xxx xxx.
</div>
<h3 style="padding-bottom: 10px;">xxx:</h3>
<p>xxx xxx.</p>
<br />
<br />
<div class="addressLine">
<asp:Label ID="lblFirstName" CssClass="addressLabel" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="txtFirstName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblLastName" CssClass="addressLabel" runat="server" Text="Last Name"></asp:Label>
<asp:TextBox ID="txtLastName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblCity" CssClass="addressLabel" runat="server" Text="City"></asp:Label>
<asp:TextBox ID="txtCity" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblDistrict" CssClass="addressLabel" runat="server" Text="District"></asp:Label>
<asp:DropDownList ID="ddlDistrict" CssClass="addressDropDown" runat="server" DataSourceID="dsDistricts"
DataTextField="Name" DataValueField="DistrictID"
AppendDataBoundItems="True">
<asp:ListItem Value="">All Districts</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<asp:Label ID="lblSpecialty" CssClass="addressLabel" runat="server" Text="Specialty"></asp:Label>
<asp:DropDownList ID="ddlSpecialty" CssClass="addressDropDown" runat="server"
DataSourceID="dsSpecialties" DataTextField="xxx_certification"
DataValueField="QualificationID" AppendDataBoundItems="True">
<asp:ListItem Value="">All xxx</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<div class="addressLabel"> </div>
<asp:LinkButton ID="lnkSearch" CssClass="navButton" runat="server"
onclick="lnkSearch_Click">Search</asp:LinkButton>
</div>
</asp:Panel>
<asp:LinqDataSource ID="dsDistricts" runat="server"
ContextTypeName="org.Xrm.XrmDataContext" Select="new (DistrictID, Name)"
TableName="Districts">
</asp:LinqDataSource>
<asp:LinqDataSource ID="dsSpecialties" runat="server"
ContextTypeName="org.Xrm.XrmDataContext"
Select="new (QualificationID, xxx_certification)" TableName="Qualifications"
Where="EducationTypeID == #EducationTypeID">
<whereparameters>
<asp:Parameter DefaultValue="000" Name="EducationTypeID"
DbType="Guid" />
</whereparameters>
</asp:LinqDataSource>
<!--//////////// Begin Search Results Panel ////////////-->
<asp:Panel ID="pnlResults" Visible="false" runat="server">
<div id="ResultsTop" style="margin-bottom: 15px;">
<div id="ResultsLeft" style="float: left; padding-top: 5px;">
<h2>Search Results - <span class="BlackResults">
<asp:Label ID="lblCount" runat="server" Text=""></asp:Label></span></h2>
</div>
</div>
<br />
<br />
<br />
<asp:LinkButton ID="lnkNewSearch" CssClass="navButtonLarge" runat="server" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager2" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<br />
<asp:ListView ID="lvResults" runat="server" DataSourceID="dsSearchResults">
<itemtemplate>
<tr style="">
<td class="DirectoryItems">
<asp:LinkButton ID="lnkDetails" CommandArgument='<%# Eval("ID") %>' OnCommand="lnkDetails_Click" runat="server"><%# Eval("xxx") %></asp:LinkButton>
</td>
<td class="DirectoryItems">
<asp:Label ID="LocationLabel" runat="server" Text='<%# Eval("Location") %>' />
</td>
<td class="DirectoryItems">
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("Status") %>' />
</td>
</tr>
</itemtemplate>
<emptydatatemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.</td>
</tr>
</table>
</emptydatatemplate>
<layouttemplate>
<table runat="server" width="100%">
<tr runat="server">
<td runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="0" style="border-collapse: collapse;" width="99%">
<tr runat="server" style="border-bottom:1px solid #828283; margin-top:5px; margin-bottom:5px; padding-top:5px; padding-bottom:5px;">
<td runat="server" width="40%">
<p class="DirectoryResultsHeader">xxx</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Location</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Status</p></td>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
</td>
</tr>
</table>
</layouttemplate>
</asp:ListView>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<asp:SqlDataSource ID="dsSearchResults" runat="server" OnSelected="dsSearchResults_Selected"
ConnectionString="<%$ ConnectionStrings:MSCRM %>" CancelSelectOnNullParameter="false"
SelectCommand="
SELECT * from sometable
">
<selectparameters>
<asp:ControlParameter ControlID="txtFirstName" DbType="String" Name="FirstName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtLastName" DbType="String" Name="LastName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtCity" DbType="String" Name="City" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="ddlDistrict" DbType="Guid" Name="District" ConvertEmptyStringToNull="true" />
<asp:ControlParameter ControlID="ddlSpecialty" DbType="Guid" Name="Specialty" ConvertEmptyStringToNull="true" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Details Panel ////////////-->
<asp:Panel ID="pnlDetails" Visible="false" runat="server">
<h3>xxx Information</h3>
<br />
<asp:Repeater ID="rpDetails" runat="server" DataSourceID="dsDetails">
<itemtemplate>
<table border="0">
<tr>
<td width="125"><b>Given Name:</b></td>
<td><%# Eval("FirstName") %></td>
</tr>
<tr>
<td width="125"><b>Surname:</b></td>
<td><%# Eval("LastName") %></td>
</tr>
<tr>
<td width="125"><b>Gender:</b></td>
<td><%#Eval("Gender") %></td>
</tr>
<tr>
<td width="125"><b>Status:</b></td>
<td><%# Eval("Status") %></td>
</tr>
<asp:Panel ID="pnlSpecialty" runat="server" Visible='<%# Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" ? true : false %>'>
<tr>
<td width="125"><b>xxx:</b></td>
<td>
<asp:Repeater ID="xxx" runat="server" DataSourceID="xxx">
<ItemTemplate>
<%# Eval("xxx") %><br />
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</asp:Panel>
<tr>
<td width="125"><b>xxx:</b></td>
<td><%# Eval("xxx") %></td>
</tr>
</table>
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:Repeater ID="rpAddresses" runat="server" DataSourceID="dsAddresses" OnItemDataBound="rpAddresses_DataBound">
<headertemplate>
<h3>xxx</h3><br />
</headertemplate>
<itemtemplate>
<table border="0">
<tr>
<td valign="top" width="125"><b><asp:Label ID="lblAddressType" runat="server" Text='<%# Eval("Type") %>' /></b></td>
<td valign="top">
<asp:Label ID="lblAddressStreet1" runat="server" Text='<%# Eval("Street1") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street1")) ? false : true %>' />
<asp:Label ID="lblAddressStreet2" runat="server" Text='<%# Eval("Street2") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street2")) ? false : true %>' />
<asp:Label ID="lblAddressStreet3" runat="server" Text='<%# Eval("Street3") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street3")) ? false : true %>' />
<asp:Label ID="lblAddressCity" runat="server" Text='<%# Eval("City") %>' />, <asp:Label ID="lblAddressProvince" runat="server" Text='<%# Eval("Province") %>' /> <asp:Label ID="lblAddressPostalCode" runat="server" Text='<%# Eval("PostalCode") %>' /><br />
<asp:Label ID="lblAddressCountry" runat="server" Text='<%# Eval("Country") + "<br />" %>' Visible='<%# (Eval("Country", "{0}") == "Canada") ? false : true %>' />
<table border="0">
<asp:Label ID="lblAddressPhone" runat="server" Text='<%# "<tr><td width=50>Phone:</td><td>" + Eval("Phone") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Phone")) ? false : true %>' />
<asp:Label ID="lblAddressFax" runat="server" Text='<%# "<tr><td width=50>Fax:</td><td>" + Eval("Fax") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Fax")) ? false : true %>' />
<asp:PlaceHolder ID="cphEmailAddress" runat="server" Visible='<%# Convert.IsDBNull(Eval("Email")) ? false : true %>'><tr><td width="50">Email:</td><td><asp:LinkButton ID="lnkEmailValidate" runat="server" Text='<%# Eval("ShortEmail") %>' OnClick="ShowReCAPTCHA" /></td></tr></asp:PlaceHolder>
<asp:PlaceHolder ID="cphEmail" runat="server" Visible="false"><tr><td width="50">Email:</td><td><asp:HyperLink ID="lnkEmail" runat="server" NavigateUrl='<%# Eval("Email", "mailto:{0}") %>' Text='<%# Eval("Email") %>' /></td></tr></asp:PlaceHolder>
</table>
<asp:PlaceHolder ID="cphCaptcha" runat="server" Visible="false">
<br />
<div class="info">To view the full email address, please type the moving characters in the box below.</div>
<nu:NuCaptchaControl ID="nucaptcha" runat="server" ClientKey="LEAP|0|4|TYPE|9|CLIENTKEY|CID|4|9942|KID|4|9884|SKEY|32|bDdiOWgwdjhtNy1MdTRENG43Q1BZdyws" />
</asp:PlaceHolder>
</td>
</tr>
</table>
<br />
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:LinkButton ID="lnkDetailsBack" CssClass="navButtonLarge" runat="server" OnClick="lnkDetailsBack_Click">Back to Search Results</asp:LinkButton>
<asp:LinkButton ID="lnkDetailsNewSearch" runat="server" CssClass="navButtonLarge" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<asp:SqlDataSource ID="dsDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsSpecialty" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsAddresses" runat="server"
ConnectionString="<%$ ConnectionStrings:xxx %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Data Sources ////////////-->
</asp:Content>
default.aspx.cs
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class directory_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack && pnlDetails.Visible == true && rpAddresses.Items.Count > 0 && ((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible == true)
{
Page.Validate();
if (Page.IsValid)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmailAddress")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmail")).Visible = true;
}
}
}
protected void rpAddresses_DataBound(object sender, EventArgs e)
{
}
protected void lnkSearch_Click(object sender, EventArgs e)
{
//lvResults.DataBind();
DataPager1.SetPageProperties(0, DataPager1.PageSize, true);
ShowResults();
}
protected void ShowResults()
{
pnlSearchbox.Visible = false;
pnlResults.Visible = true;
pnlDetails.Visible = false;
}
protected void lnkNewSearch_Click(object sender, EventArgs e)
{
pnlSearchbox.Visible = true;
pnlResults.Visible = false;
pnlDetails.Visible = false;
}
protected void lnkDetails_Click(object sender, CommandEventArgs e)
{
dsDetails.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsSpecialty.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsAddresses.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
rpAddresses.DataBind();
if (rpAddresses.Items.Count == 0)
{
rpAddresses.Visible = false;
}
else
{
rpAddresses.Visible = true;
}
pnlSearchbox.Visible = false;
pnlResults.Visible = false;
pnlDetails.Visible = true;
}
protected void lnkDetailsBack_Click(object sender, EventArgs e)
{
ShowResults();
}
protected void dsSearchResults_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
lblCount.Text = String.Format("{0} Dentists found", e.AffectedRows);
}
protected void ShowReCAPTCHA(object sender, EventArgs e)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = true;
}
}
Thanks for the answers people, I did try some of these things.
Every control which you wish to access in aspx.cs should have runat="server"
they do
Build your solution after adding the above tag
If you wish to access the control defined inside the item template of repeater you
can do so only inside repeater events for by putting a loop reading
all items of repeater
they are
Right click on the page where you are getting the error and click on
convert to web application... That will solve your error.
no such option in my IDE, besides I think it would be the whole project, not a page that I convert.
Check to see if this is a web application project or a website
project. A website project would use the CodeFile attribute of the
#Page directive, but a web application project wouldn't. If it's
trying to compile as a web application project, you would receive
these errors because a web application project expects a designer file
in addition to the .aspx and .aspx.cs files. The designer contains all
the control definitions which in turn which allows you to reference
them properly in codebehind (web application uses CodeBehind and not
CodeFile attribute as well).
apparently then my project is a website, not a web application, as it includes the codefile attribute. also, I don't have designer files, so this makes sense.
Turns out I am trying to edit a solution developed in VS2008, using VS2013, and a lot has changed since then. While the issue was not resolved here, the fix was to create a new VS2013 solution and import the files, it's all working as intended now, thank you.
exclude or delete any other pages that reference the same code-behind file, for example an older page that you copied and pasted.
You may want to check the build action of the c# files in the property window in visual studio and make sure its set to Compile
Check to see if this is a web application project or a website project. A website project would use the CodeFile attribute of the #Page directive, but a web application project wouldn't. If it's trying to compile as a web application project, you would receive these errors because a web application project expects a designer file in addition to the .aspx and .aspx.cs files. The designer contains all the control definitions which in turn which allows you to reference them properly in codebehind (web application uses CodeBehind and not CodeFile attribute as well).
Right click on the page where you are getting the error and click on convert to web application... That will solve your error.
Couple of things to be checked here:
1. Every control which you wish to access in aspx.cs should have runat="server"
2. Build your solution after adding the above tag
3. If you wish to access the control defined inside the item template of repeater you can do so only inside repeater events for by putting a loop reading all items of repeater
I had this error but had just made a silly mistake. I wanted to retain the original code while I made some big changes so I copied and pasted one of the .cs files. Well, both files had the same class name. The two identical namespaces (understandably) confused the compiler. Removing the "backup" fixed it. I could have just changed the namespace, too.
Just sharing in case someone is as bone-headed as I.

If checkbox checked and textbox blank

I have a checkbox, on click of which the textbox gets enabled. I want to make validation that If checkbox is checked and the user doesn't put any data. It should not allow the user to submit the form. Please see the javascript code for your reference
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$('#chkCropLoan').change(function () {
$("#txtAmount").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtAmount").val("");
}
});
$('#chkInvestmentLoan').change(function () {
$("#txtInvestmentLoan").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtInvestmentLoan").val("");
}
});
$('#chkWarehouseReceipt').change(function () {
$("#txtWarehouseReceipt").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtWarehouseReceipt").val("");
}
});
$('#chkFarmerProd').change(function () {
$("#txtFarmerProd").prop("disabled", !$(this).is(':checked'));
if (!$(this).is(':checked')) {
$("#txtFarmerProd").val("");
}
});
});
</script>
HTML code of textbox :
<table>
<tr>
<td>Crop Loan</td>
<td>
<asp:CheckBox ID="chkCropLoan" runat="server" CssClass="check" onclick="javascript:enableTextBox();" />
<asp:TextBox ID="txtAmount" runat="server" class="txtfld-popup1" MaxLength="5" Width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtAmount_TextBoxWatermarkExtender" runat="server" TargetControlID="txtAmount" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
<asp:RegularExpressionValidator ID="rgfldvalidator" ControlToValidate="txtAmount"
runat="server" ErrorMessage="Please enter the numbers only" ValidationExpression="^[0-9]*\.?[0-9]+$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Investment Loan</td>
<td>
<asp:CheckBox ID="chkInvestmentLoan" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtInvestmentLoan" runat="server" class="txtfld-popup1" MaxLength="5" width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtInvestmentLoan_TextBoxWatermarkExtender" runat="server" TargetControlID="txtInvestmentLoan" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" ControlToValidate="txtInvestmentLoan"
runat="server" ErrorMessage="Please enter the numbers only" ValidationExpression="^[0-9]*\.?[0-9]+$"></asp:RegularExpressionValidator>
</td>
</tr>
</tr>
<tr>
<td>Warehouse Receipt Finance</td>
<td>
<asp:CheckBox ID="chkWarehouseReceipt" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtWarehouseReceipt" runat="server" class="txtfld-popup1" MaxLength="5" Width="100" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtWarehouseReceipt_TextBoxWatermarkExtender" runat="server" TargetControlID="txtWarehouseReceipt" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
</td>
</tr>
<tr>
<td>Farmer Producer Companies</td>
<td>
<asp:CheckBox ID="chkFarmerProd" runat="server" CssClass="check" OnChange="javascript:enableTextBox();" />
<asp:TextBox ID="txtFarmerProd" runat="server" class="txtfld-popup1" MaxLength="5" onkeypress="if(event.keyCode<48 || event.keyCode>57)event.returnValue=false;" Width="100" Enabled="false"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender11" runat="server" TargetControlID="txtFarmerProd" WatermarkText="Amount"></cc1:TextBoxWatermarkExtender>
</td>
</tr>
</table>
Try:
$("#your-form").submit(function() {
if($(this).find("#your-text").val() && $(this).find("#your-check").checked){
$("#your-form").submit();
}
else{
// not checked or empty textbox
}
return false;
});
Try using the below code:
$('#your_form_name').submit(function( event ) {
if ($('#chkCropLoan').is(':checked') && $('#txtAmount').val() == '') {
alert('error message');
event.preventDefault();
}
});
you don't want to submit form if Text box is Empty
just write function on submit button click event
<input type="submit" value="save" onclick="return checkvalid()" />
In script
<script type="text/javascript">
function checkvalid() {
if (document.getElementById('textboxId').value==""
|| document.getElementById('textboxId').value==undefined) {
return false;
}
</script>

why is my page passing a blank value for my textBox

I asked this question last night but it was not very well written so I am going to ask it again. I am creating a simple calculator using ASP.NET and c# as my code behind. I am currently just trying to test and make sure that my code behind is getting the value typed entered into the textbox by the user. I put in a if statement that assigns the textbox a value of mehhh if the string it gets passed it empty. My text box displays mehhh so I knoe it is getting an empty string but i am not sure why? here is a link to the site... http://scort323.csweb.kutztown.edu/Calc.aspx Below is my code for the code behind part of my page:
public partial class Assign2_Calc : System.Web.UI.Page
{
protected void ButtonEqual_Click(object sender, EventArgs e)
{
string inputStr = inputBox.Text;
if (inputStr == string.Empty)
{
inputBox.Text = "mehhhhhh";
}
else
{
inputBox.Text = inputStr; //result.ToString();
}
}
}
below is my .aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Calc.aspx.cs"
Inherits="Assign2_Calc" Debug="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="CalculatorStyle.css" rel="stylesheet" type="text/css" />
<script>
var maxInputLength = 20;
function checkButtonClick(clickedValue) {
var buttonValue = clickedValue;
var inputStr = document.getElementById('inputBox').value;
if (buttonValue == '<--') {
if (inputStr.length >= 1) {
document.getElementById('inputBox').value = inputStr.substring(0, inputStr.length - 1);
}
}
else if (buttonValue == 'C') {
document.getElementById('inputBox').value = "";
}
else {
if (inputStr.length < maxInputLength) {
document.getElementById('inputBox').value = inputStr + buttonValue;
}
else {
//document.getElementById('msg').innerHTML = "Maxmum length is " + maxInputLength;
}
}
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="main" class="main">
<div id="content" class="content">
<h3 id="h3">Simple Calculator</h3>
<div id="calculatorDiv">
<table cellpadding="0" cellspacing="0">
<tr>
<td colspan="4">
<asp:TextBox runat="server" CssClass="inputBox" ReadOnly="true" ViewStateMode="Enabled" ID="inputBox"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="4">
<br />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonNum7" runat="server" Text="7" CssClass="CalcButtons" OnClientClick="return checkButtonClick(7)" />
</td>
<td>
<asp:Button ID="ButtonNum8" runat="server" Text="8" CssClass="CalcButtons" OnClientClick="return checkButtonClick(8)" />
</td>
<td>
<asp:Button ID="ButtonNum9" runat="server" Text="9" CssClass="CalcButtons" OnClientClick="return checkButtonClick(9)" />
</td>
<td>
<asp:Button ID="ButtonDivide" runat="server" Text="/" CssClass="CalcButtons" OnClientClick="return checkButtonClick('/')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonNum4" runat="server" Text="4" CssClass="CalcButtons" OnClientClick="return checkButtonClick(4)" />
</td>
<td>
<asp:Button ID="ButtonNum5" runat="server" Text="5" CssClass="CalcButtons" OnClientClick="return checkButtonClick(5)" />
</td>
<td>
<asp:Button ID="ButtonNum6" runat="server" Text="6" CssClass="CalcButtons" OnClientClick="return checkButtonClick(6)" />
</td>
<td>
<asp:Button ID="ButtonMultiply" runat="server" Text="*" CssClass="CalcButtons" OnClientClick="return checkButtonClick('*')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="1" CssClass="CalcButtons" OnClientClick="return checkButtonClick(1)" />
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="2" CssClass="CalcButtons" OnClientClick="return checkButtonClick(2)" />
</td>
<td>
<asp:Button ID="Button3" runat="server" Text="3" CssClass="CalcButtons" OnClientClick="return checkButtonClick(3)" />
</td>
<td>
<asp:Button ID="ButtonSubtract" runat="server" Text="-" CssClass="CalcButtons" OnClientClick="return checkButtonClick('-')" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonDackspace" runat="server" Text="<--" CssClass="CalcButtons" OnClientClick="return checkButtonClick('<--')" />
</td>
<td>
<asp:Button ID="ButtonNum0" runat="server" Text="0" CssClass="CalcButtons" OnClientClick="return checkButtonClick(0)" />
</td>
<td>
<asp:Button ID="ButtonClear" runat="server" Text="C" CssClass="CalcButtons" OnClientClick="return checkButtonClick('C')" />
</td>
<td>
<asp:Button ID="ButtonAdd" runat="server" Text="+" CssClass="CalcButtons" OnClientClick="return checkButtonClick('+')" />
</td>
</tr>
<tr>
<td colspan="4">
<asp:Button ID="ButtonEqual" runat="server" Text="=" CssClass="CalcButtonEqual" OnClick="ButtonEqual_Click" />
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Looking at the source of your web page I found that you have disabled your textbox. If a control is disabled it cannot be edited and its content is excluded when the form is submitted. So instead of disabling (remove disable attribute completely) your textbox set it to readonly (readonly = 'true').
MSDN doc on ReadOnly:
The Text value of a TextBox control with the ReadOnly property set to true is sent to the server when a postback occurs, but the server does no processing for a read-only text box. This prevents a malicious user from changing a Text value that is read-only. The value of the Text property is preserved in the view state between postbacks unless modified by server-side code.
You are "manipulating" the value in client script (not in server code - assuming above is all the code). The original value of the TextBox is preserved (empty).
If you test by removing the ReadOnly attribute (or set it to False), your code will work and you will see the effect of the setting...
Hth....
Update:
..how would I need to go about making it so the user cant use the keyboard to enter anything? making it so they must use the buttons
Unless you have/had a reason to use a server-side control for that input field, a standard HTML Input field with readonly should work.
You will then obtain it's value from the standard POST in the Request (at the end of the day, WebForms is still an HTTP POST), instead of ASP.Net controls.
Trivial example:
Instead of server-control:
<asp:TextBox runat="server" CssClass="inputBox" ReadOnly="true" ViewStateMode="Enabled" ID="inputBox"></asp:TextBox>
Use plain html input field:
<input id="inputBox" name="inputBox" readonly type="text" />
The value of the field (html_readonly) can be obtained in the POST Request:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string _html = Request["inputBox"]; //here it is
//do whatever...
}
}
Hth...

Setting visibility of a link in code behind

i have this in source code:
<a href="CreateAlbum.aspx" id="createalbumlink">
Create New Album
</a>
now i want to set its visibility in code behind. How can i do so? I have this link within ListView Control.
I replaced the above with
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
still couldnt detect in codebehind.
SOurce code:
<form id="form1" runat="server">
<asp:ListView ID="lvAlbums" runat="server"
DataSourceID="SqlDataSource1" GroupItemCount="3"
InsertItemPosition="LastItem">
<LayoutTemplate>
<table border="1">
<tr ID="groupPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<td ID="itemPlaceholder" runat="server">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td3" width="150px" height="150px" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:HiddenField ID="hfPhotoID" runat="server" Value='<%# Eval("DefaultPhotID") %>' />
<a href='<%# "Photos.aspx?AlbumID="+Eval("AlbumID") %>'>
<asp:Image CssClass="Timg" runat="server" ID="imPhoto" ImageUrl='<%# "ThumbNail.ashx?ImURL="+Eval("Photo") %>' />
</a>
<br />
<b><asp:Label ID="lblAlbumName" runat="server" Text='<%# Eval("AlbumName") %>'></asp:Label> </b>
</td>
</ItemTemplate>
<InsertItemTemplate>
<td id="Td3" width="150px" height="150px" runat="server" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
<%-- <a href="CreateAlbum.aspx" id="createalbumlink" runat="server">
Create New Album
</a>--%>
</td>
</InsertItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SLIITComDBConnectionString %>"
SelectCommand="SELECT Album.AlbumID, Album.DefaultPhotID, Album.AlbumName, PhotAlbum.Photo FROM Album INNER JOIN PhotAlbum ON Album.DefaultPhotID = PhotAlbum.PhotoID where album.userid=#userid">
<SelectParameters>
<asp:QueryStringParameter Name="userid" Type="int32" QueryStringField="id" />
<%--<asp:SessionParameter Name="userid" Type="String" SessionField="UserId" />--%>
</SelectParameters>
</asp:SqlDataSource>
</form>
Well you can't access the LinkButton directly since its inside a ListView, you can iterate through each item in the ListView and find the link button using FindControl and then set the Visible property. Something like:
foreach (ListViewItem item in listView.Items)
{
LinkButton linkButton = item.FindControl("LinkButton1") as LinkButton;
if (linkButton != null)
linkButton.Visible = false;
}
the above will disable LinkButton for all the items.
Use the OnClick event handler of the LinkButton and toggle the visibility there.
Somewhere in the code behind do this:
LinkButton1.Visible = false;
LinkButton1.Visible = false; //control will not rendered
LinkButton1.Attribute["styles"] = "display:none"; // control will be hidden
You can alse use tag, but you have to add runat="server" param
Edit
Try using FindControl:
LinkButton LinkButton1 = (LinkButton)ListView1.FindControl("LinkButton1");
LinkButton1.Visible = false;

Two ModalPopupExtenders used in the same way, only one works

Within a gridview, I have an "Email" button and a "Delete" button that opens up a Modal popup window using the modalpopupextender. The problem is that the Email window opens when the button is clicked, but the Delete window does not open when its button is clicked. I am using both modalpopupextenders in the same way.
<asp:ButtonField ButtonType="Button" CommandName="Email" Text="Email" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
<%-- Email modal--%>
<asp:Panel ID="pnlPopupEmail" runat="server" Width="500px" Style="display: none">
<asp:UpdatePanel ID="updPnlEmail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnShowEmail" runat="server" Style="display: none" />
<ajaxToolkit:ModalPopupExtender ID="mdlPopupEmail" runat="server" TargetControlID="btnShowEmail"
PopupControlID="pnlPopupEmail" CancelControlID="btnCancel" BackgroundCssClass="modalBackground" />
<div class="EmailPopup">
<table>
<tr>
<td>
To:
</td>
<td>
<asp:TextBox ID="EmailTo" runat="server" Width="350"></asp:TextBox>
</td>
</tr>
<tr>
<td>
From:
</td>
<td>
<asp:TextBox ID="EmailFrom" runat="server" Width="350"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<asp:TextBox ID="Subject" runat="server" Width="350"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td> <asp:TextBox ID="EmailMessageBox" Width="350" Height="150" runat="server" TextMode="MultiLine" Wrap="true"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:LinkButton ID="SendBtn" runat="server" OnClick="SendBtn_Clicked" Text="Send" />
<asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" />
</td>
<td>
<asp:Label ID="theID" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<%-- -----end email modal--%>
<%-- Start Delete Confirmation Modal --%>
<asp:Panel ID="DelConfirmPanel" runat="server" Width="500px" Style="display: none">
<asp:UpdatePanel ID="DelConfirmUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID ="TESTLabel" runat="server" Text="Are you sure?" ></asp:Label>
<asp:Button ID="DelModalButton" runat="server" Style="display: none" />
<ajaxToolkit:ModalPopupExtender ID="modalPopUpDelConfirm" runat="server" TargetControlID="DelModalButton"
PopupControlID="DelConfirmPanel" CancelControlID="DeleteCancel" BackgroundCssClass="modalBackground" />
<div class="DeletePopup">
<asp:LinkButton ID="DelConfirmedButton" runat="server" OnClick="DeleteConfirmation_Clicked"
Text="Delete" />
<asp:LinkButton ID="DeleteCancel" runat="server" Text="Cancel" CausesValidation="false" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<%-- End Delete Confirmation Modal --%>
</div>
Then in the codebehind I have a method that checks the command name and updates the updatepanel and shows the modalpopupextender.
protected void btn_Clicked(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
// a bunch of stuff that I am leaving out but is just changing fields in the
//table withing the modal popup
updPnlEmail.Update();
mdlPopupEmail.show();
}
if (e.CommandName.Equals("Delete"))
{
int index = Convert.ToInt32(e.CommandArgument);
String id = gvReservations.DataKeys[index].Value.ToString(); // get id
try
{
DelConfirmUpdatePanel.Update();
modalPopUpDelConfirm.Show();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Any ideas why one works and not the other? Is there a good way to debug this kind of error? Thanks a lot for any help!
Figured it out.
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
This is where the problem was. I didn't realize that "Delete" was a reserved command name. So when this button was clicked an exception was being thrown saying that it couldn't delete from the table. Thus, the modal popup was never being shown. I figured it out by opening the javascript console in the chrome tools.
So to fix it, I changed the command name to something else and now everything works as expected.

Categories

Resources