Use asp.net button onclick method instead of submitting form - c#

I have an asp.net Button control which I want to use to insert comments in my page. When i click on button, I want it to call a method instead of submitting the form. How do i achieve this?
This is what i have tried so far -
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
//Do some stuff here
}
</script>
<head>title and other css links go here</head>
<body>
<form id="form1" runat="server" onsubmit="false">
//Some other asp.net controls go here
<asp:Button ID="Button1" runat="server" Text="Comment" OnClick="Button1_Click"/>
</form>
</body>
</html>
Is there any other way to achieve what I am doing? Suggestions are welcome.

I don't really know exactly what you are meaning.... I think you are asking for how to insert a comment into an aspx via a shout box???... Maybe?
Here is the code to insert whatever you want to type(a comment) into your form from a "method"... although it uses a lot more than just a single method.. this is the simplest way I can think of...
This is your default.aspx (notice no master page here)
<!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 id="Head1" runat="server">
<title>AJAX Example for comment</title>
<link href="Main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id="page">
<div id="main">
<div id="shoutbox">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>Here's what everyone is saying:</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblShoutBox" runat="server"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="5000">
</asp:Timer>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddShout"
EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p class="label">Name:</p>
<p class="entry">
<asp:TextBox ID="txtUserName" runat="server"
MaxLength="15" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ErrorMessage="Name is required."
ControlToValidate="txtUserName" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<p class="label">Shout:</p>
<p class="entry">
<asp:TextBox ID="txtShout" runat="server"
MaxLength="255" Width="220px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server" ErrorMessage="Shout is required."
ControlToValidate="txtShout" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<asp:Button ID="btnAddShout" runat="server" Text="Add Shout"
onclick="btnAddShout_Click" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
DynamicLayout="False">
<ProgressTemplate>
<img src="Images/spinner.gif" alt="Please Wait" />
Comment...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</p>
</div>
</div>
</div>
</form>
</body>
</html>
And this is your C# Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShoutItemList shoutBox;
if (Application["ShoutBox"] == null)
{
shoutBox = new ShoutItemList();
Application.Add("ShoutBox", shoutBox);
}
else
{
shoutBox = (ShoutItemList)Application["ShoutBox"];
lblShoutBox.Text = shoutBox.Display();
}
if (ScriptManager1.IsInAsyncPostBack != true)
txtUserName.Focus();
}
protected void btnAddShout_Click(object sender, EventArgs e)
{
ShoutItem shout = new ShoutItem();
shout.UserName = txtUserName.Text;
shout.Comment = txtShout.Text;
shout.Timestamp = DateTime.Now;
Application.Lock();
ShoutItemList shoutBox = (ShoutItemList)Application["ShoutBox"];
shoutBox.Add(shout);
Application.UnLock();
lblShoutBox.Text = shoutBox.Display();
txtShout.Text = "";
txtShout.Focus();
}
}
public class ShoutItem
{
public string UserName { get; set; }
public DateTime Timestamp { get; set; }
public string Comment { get; set; }
}
public class ShoutItemList
{
private List<ShoutItem> shoutList = new List<ShoutItem>();
private void Purge()
{
DateTime purgeTime = DateTime.Now;
purgeTime = purgeTime.AddMinutes(-3);
int i = 0;
while (i < shoutList.Count)
{
if (shoutList[i].Timestamp <= purgeTime) shoutList.RemoveAt(i);
else i += 1;
}
}
public void Add(ShoutItem shout)
{
Purge();
System.Threading.Thread.Sleep(2000);
shoutList.Insert(0, shout);
}
public string Display()
{
Purge();
StringBuilder shoutBoxText = new StringBuilder();
if (shoutList.Count > 0)
{
shoutBoxText.AppendLine("<dl>");
foreach (ShoutItem shout in shoutList)
{
shoutBoxText.Append("<dt>" + shout.UserName + " (");
shoutBoxText.Append(shout.Timestamp.ToShortTimeString() + ")</dt>");
shoutBoxText.AppendLine("<dd>" + shout.Comment + "</dd>");
}
shoutBoxText.AppendLine("</dl>");
}
return shoutBoxText.ToString();
}
}
This will allow you to insert whatever comment you want. You can modify this code to your own please....
Let me know if this is the answer you seek.

Use the button's OnClientClick, like this:
<asp:Button ID="Button1" runat="server" Text="Comment" OnClientClick="return javascriptFunction();" OnClick="Button1_Click"/>
then your javascript function would look like this
function javascriptFunction() {
//do something here
return false; //if you don't want the form to POST to the server, leave this as false, otherwise true will let it continue with the POST
}

Related

Chat Application using Asp.net giving Database errors

I am making a Chat Application in ASP.NET using AJAX,LINQ to SQL and some security features for authentication purpose.The Chat will be according to a specific group.I am getting an error after I attempt to login to the Chat page(default.aspx,in my project) ,
the error is :
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tbmsg_tbusr2". The conflict occurred in database "test", table "dbo.tbusr", column 'usrcod'.
The statement has been terminated."
Note : tbmsg is a table for storing data about messages and tbusr for storing data about users.
The Back end Code for Default.aspx is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
chatDataContext obj = new chatDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Label1.Text = "Welcome:" + Session["usrnam"].ToString();
Insert_Msg("Just Login:");
GetLoggedUser();
Get_Msg();
}
}
private void Insert_Msg(String m)
{
tbmsg k = new tbmsg { msgdsc = m, msgdat = DateTime.Now, msgfrmusrcod = Convert.ToInt32(Session["usrcod"]), msgtousrcod = null, msggrpcod = Convert.ToInt32(Request.QueryString["grpcod"]) };
obj.tbmsgs.InsertOnSubmit(k);
obj.SubmitChanges();
}
private void Get_Msg()
{
var q = from p in obj.tbmsgs
where p.msggrpcod == Convert.ToInt32(Request.QueryString["grpcod"])
select p;
StringBuilder sb = new StringBuilder();
foreach (var t in q)
{
sb.Append(t.msgdsc + ":" + t.msgdat.ToString() + ":" + t.tbusr.usrnam + "<br/>");
}
ltmsg.Text = sb.ToString();
}
private void GetLoggedUser()
{
var q = (from p in obj.tblogusrs where p.logusrusrcod == Convert.ToInt32(Session["usrcod"]) select p).SingleOrDefault();
if (q == null)
{
tblogusr x = new tblogusr { logusrusrcod = Convert.ToInt32(Session["usrcod"]), logusrgrpcod = Convert.ToInt32(Request.QueryString["grpcod"]) };
obj.tblogusrs.InsertOnSubmit(x);
obj.SubmitChanges();
}
StringBuilder sb = new StringBuilder();
var q1 = from p in obj.tblogusrs where p.logusrgrpcod == Convert.ToInt32(Request.QueryString["grpcod"]) select p;
foreach (var t in q1)
{
sb.Append(t.tbusr.usrnam + "<br/>");
}
ltuser.Text = sb.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Length > 0)
{
Insert_Msg(TextBox1.Text);
TextBox1.Text = String.Empty;
TextBox1.Focus();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
var q = (from p in obj.tblogusrs where p.logusrusrcod == Convert.ToInt32(Session["usrcod"]) select p).SingleOrDefault();
if (q != null)
{
obj.tblogusrs.DeleteOnSubmit(q);
obj.SubmitChanges();
}
Insert_Msg("Just Logout:");
FormsAuthentication.SignOut();
Response.Redirect("login.aspx");
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Get_Msg();
GetLoggedUser();
}
}
The HTML Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1
{
width: 70%;
height: 25px;
}
.auto-style2
{
height: 25px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 286px; width: 849px">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
</asp:Timer>
<table border="5" style="width: 100%; margin-right: 0px">
<tr>
<td width="30%" class="auto-style2">
<asp:Literal ID="ltuser" runat="server" />
</td>
<td class="auto-style1">
<asp:Literal ID="ltmsg" runat="server" />
</td>
</tr>
</table>
<br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send" />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Logout" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Description for tbusr table:
usrcod int primary key (auto increment)
usrnam varchar(50)
usrpwd varchar(50)
Description for tbmsg table:
msgcod int primary key (auto increment)
msgdsc varchar(100)
msgdat datetime
msgfrmusrcod int (foreign key with usrcod of tbusr)
msgtousrcod int (foreign key with usrcod of tbusr)
msggrpcod int (foreign key with grpcod of tbgrp)
Note : tbgrp is another table for storing data about groups

Cannot Unregister UpdatePanel exception with Cross Page Posting

I am getting the dreaded exception "Cannot unregister UpdatePanel with ID 'UpdatePanel' since it was not registered with the ScriptManager" when trying to combine a popup window and some Cross-Page Posting. I've been able to reproduce the problem with a small example.
I have seen other questions that handle the Unload event for the UpdatePanel, but that doesn't seem to work with the addition of the Cross Page Posting.
How do I get around this issue?
To duplicate the issue with the code below:
Start the Setup page
Press the View Popup link
Close the popup
Press the Next button to transfer to the Target page
Press the Back button to transfer to the Setup page
Press the View link and close the popup
Press the Next button, and see the failure
Here are the highlights (forgive the length, but it should be cut-and-pastable):
Setup.aspx
<head runat="server">
<title>Setup </title>
<script type="text/javascript">
function openCenteredWindow(url, height, width, name, parms) {
//Snip setting up window location stuff
var win = window.open(url, name, winParms);
return win;
}
</script>
</head>
<body>
<h1>Setup Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:TextBox ID="txtData" runat="server" Width="80%" Text="<%# Information %>" />
<br />
<asp:LinkButton ID="lbViewData" runat="server"
OnClientClick="aspnetForm.target='ViewDataPopup';"
Text="View In Popup" /> <br />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
</div>
<div>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:updatepanel ID="UpdatePanel" runat="server" OnUnload="UpdatePanel_Unload"></asp:updatepanel>
</div>
</form>
</body>
Setup.Aspx.cs
public partial class Setup : System.Web.UI.Page
{
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (this.ViewState["Information"] != null)
_Information = this.ViewState["Information"].ToString();
}
protected override object SaveViewState()
{
this.ViewState["Information"] = _Information;
return base.SaveViewState();
}
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage is TargetPage)
{
_Information = ((TargetPage)PreviousPage).SetupData;
}
else if (!Page.IsPostBack)
{
_Information = String.Format("This test started at {0}", DateTime.Now);
}
Page.DataBind();
lbViewData.PostBackUrl = "ViewData.aspx?u=0";
lbViewData.Attributes.Add("onclick", "JavaScript:openCenteredWindow(\"ViewData.aspx?u=0\", 400, 300, \"ViewDataPopup\", 'scrollbars=yes');");
}
private string _Information;
public string Information
{
get { return _Information; }
}
protected void btnNext_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/TargetPage.aspx");
}
}
ViewData.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title>View Data</title>
<script type="text/javascript">
function fixForm() {
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = "";
}
</script>
</head>
<body onload="fixForm()">
<form id="aspnetForm" runat="server">
<div>
<h2 >View Data</h2>
</div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" />
</form>
</body>
ViewData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
Setup setup = (Setup)PreviousPage;
this.SetupData = setup.Information ?? "Data not set in Setup Page";
}
Page.DataBind();
}
private string _setupData = "Did not get updated data";
protected string SetupData
{
get { return _setupData; }
set { _setupData = value; }
}
TargetPage.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<body style="background-color: #9999BB">
<h1>Target Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" /><br />
<asp:Button ID="btnBack" runat="server" Text="Back" OnClick="btnBack_Click" />
</div>
</form>
</body>
TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.PreviousPage == null)
Response.Redirect("Setup.aspx");
this.SetupData = PreviousPage.Information;
}
Page.DataBind();
}
public string SetupData
{
get { return ViewState["SetupData"].ToString(); }
set { ViewState["SetupData"] = value; }
}
protected void btnBack_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/Setup.aspx");
}
As you can see, it's enough to have the UpdatePanel just sitting on the page and doing nothing for this error to occur.

How can I add selected value in an asp.net ajax toolbox autocomplete to a label?

I have got the Ajax toolkit autocomplete working using the following asp.net and C# code.
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
Search our Languages: <asp:TextBox ID="txtLanguage" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtLanguage" MinimumPrefixLength="1"
ServiceMethod="GetCompletionList" UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<br />
<asp:Button ID="btnAddSelected" runat="server" Text="Add to chosen Languages >"
onclick="btnAddSelected_Click" />
<br />
<br />
<asp:Label ID="lblSelectedLanguages" runat="server" Text=""></asp:Label>
</div>
</form>
This is my codebehind C#:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
// Create array of languages.
string[] languages = { "Afrikaans", "Albanian", "Amharic", "Arabic", "Azerbaijani", "Basque", "Belarusian", "Bengali", "Bosnian", "Bulgarian" };
// Return matching languages.
return (from l in languages where l.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select l).Take(count).ToArray();
}
protected void btnAddSelected_Click(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
The selected language is added to the label when the button is clicked, however I would like to remove the button and make the selected item from the autocomplete added to the label automatically, using the partial postback from the Ajax toolkit.
Can someone please advise as to how I can achieve this?
Thanks.
Handle OnClientItemSelected on the AutoCompleteExtender control to run a javascript function
All the javascript does is simply fire off the TextChanged event when the selection is made (works on both Enter and left click)
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function ItemSelected(sender, args) {
__doPostBack(sender.get_element().name, "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Search our Languages:
<asp:TextBox ID="txtLanguage" autocomplete="off" runat="server" OnTextChanged="TextChanged" />
<asp:AutoCompleteExtender OnClientItemSelected="ItemSelected" ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtLanguage" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"
UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<asp:Label ID="lblSelectedLanguages" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
Code behind:
protected void TextChanged(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
It looks like you just need to hook onto the on text changed event of your text box and then put your logic in code benind.Something like this
Markup
<asp:TextBox ID="txtLanguage" OnTextChanged="txtLanguage_textChanged" AutoPostback="true" />
Then in your code behind
protected void txtLanguage_textChanged(object sender, EventArgs e)
{
//use the retrieved text the way you like
lblSelectedLanguages.Text =txtLanguage.Text;
}
Hope this helps.I would also suggest that you try looking into the JQuery autocomplete widget.It has brought me sheer happiness and I surely did divorce the autocomplete extender.
Jquery Autocomplete

Label does not exist in the current context of asp.net page and ajax control

before I begin, there is another question with a similar title and it is unsolved but my situation is pretty different since I am using Ajax.
I recently added a label to my Ajax UpdateProgress control and for some reason my asp.net page is not reading it. My original goal was for the text of the label to be constantly be updating while the long method runs. I am using code behind, and I believe the label is declared. I will post my .cs page if anyone would like to read through it (its not too long), All my other labels work perfectly and even if I take the label OUT of the ajax control it will work fine (not the text updates though). Is there a certain Ajax label I need to use?
Im pretty confused why the error is occurring. The exact error message states : "The name 'lblProgress' does not exist in the current context. Im using c#, ajax controls, a asp.net page, and visual studio. This program uploads a file to a client and stores the information in a database. If anyone can help I would really appreciate it. Thanks in advance!
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Threading;
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
lblProgress.Visible = true;
lblProgress.Text = "Preparing System Checks...";
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
lblProgress.Text = "Locating Files...";
//bf.ReadyFilesForTransmission();
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
lblProgress.Text = "Sending Files to Kaplan...";
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
lblProgress.Text = "Uploading File Info to Database...";
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = true;
SuccessLabel.Visible = false;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
Here is my aspx code as well.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SendOrders.aspx.cs" Inherits="SendOrders" %>
<!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 id="Head1" runat="server">
<title>Kaplan EDI Manager</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 220px;
height: 19px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="mainPanel">
<div>
<h3>Number of Batches Created Today: <asp:Label runat="server" style="display:inline;" ID="BatchesCreatedLbl"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<span class="red">COUNTDOWN TO SUBMISSION!</span>
<span id="timespan" class="red"></span>
</h3>
</div>
<div id="batchestoprocessdiv">
</div>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="BatchesToProcessLbl" runat="server" CssClass="green"
Height="22px" Text="THERE IS AN ORDER BATCH TO PROCESS."></asp:Label>
<asp:Label ID="NoBatchesToProcessLbl" runat="server" CssClass="red"
Text="There are no Order Batches to Process." Visible="false"></asp:Label>
<asp:Button ID="PutFTPButton" runat="server" onclick="Button_Click"
Text="Submit Orders" />
<asp:Label ID="SuccessLabel" runat="server" CssClass="green"
Text="Batch has been processed and uploaded successfully." Visible="false"></asp:Label>
<asp:Label ID="ErrorLabel" runat="server" CssClass="red" Text="Error: "
Visible="false"></asp:Label>
<asp:Label ID="lblProgress" runat="server" CssClass="green" Height="16px"
Text="Label" Visible="False"></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<br />
<img alt="" class="style1" src="images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</div>
<div id="OrdersInfoDiv" runat="server" visible="false">
<asp:GridView ID="BatchDetails" Caption="Details of orders ready to be sent" runat="server" AutoGenerateColumns="true"
CssClass="InfoTable" AlternatingRowStyle-CssClass="InfoTableAlternateRow" >
</asp:GridView>
</div>
<div id="OrdersSentDiv" class="mainPanel" runat="server" visible="false">
<h4>Sent Orders</h4>
</div>
</form>
<script src="js/SendOrders.js" type="text/javascript"></script>
</body>
</html>
If the Label is created inside the UpdateProgress control, then you will need to do something like this
((Label)upUpdateProgress.FindControl("lblProgress")).Text = "Uploading File...";
If the control is declared in markup and the code-behind doesn't recognize it, then your designer.cs file is probably out of sync. There are a few ways to fix this:
Close the form and reopen it, and remove and add lblProgress again
Add the Label to the designer.cs file manually
Here's how to add it manually:
/// <summary>
/// lblProgress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProgress;
EDIT
Just noticed that you're putting the UpdatePanel in an UpdateProgress control, in which case you'll need to reference it using FindControl (like #Valeklosse) suggested.

Displaying sourcecode when clicking a button

First I have to let you know that i am a newbie in this area, learning from tutorials.
With that said I'm looking for a way to load sourcecode from the codebehind file into a textbox, when clicking a button. Same goes for the aspx file.
Im making this website, where i am going to show code examples from what im doing. So if I navigate to myweb.com/tutorial1done.aspx this page would show me the final result from the tutorial done. When i click the show source button it should make 2 textboxes visible, and add the codebehind to the first box, and the aspx source to the second box.
I don't know if it is possible, but I am hoping so.
This far i have this:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DateTimeOutput.aspx.cs" Inherits="WebApplication1.DateTimeOutput" %>
<!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">
<title></title>
<link rel="stylesheet" href="../styles/codeformatter.css" />
</head>
<body>
<form id="form1" runat="server">
<customControls:Header runat="server" heading="Date and Time Output" />
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:TextBox ID="outputText" runat="server" Height="175px" TextMode="MultiLine"
Width="400px"></asp:TextBox>
</asp:Panel>
</div>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="runButton" runat="server" Text="Run Code"
onclick="runButton_Click" Width="95px" />
<asp:Button ID="clearButton" runat="server" Text="Clear Console"
onclick="clearButton_Click" Width="95px" />
<br />
<br />
<asp:Button ID="dt_showSource_btn" runat="server"
onclick="dt_showSource_btn_Click" Text="Show Source" />
</asp:Panel>
<asp:Label ID="dtLabel1" runat="server" Text="Code Behind:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtcb_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
<br />
<br />
<asp:Label ID="dtLabel2" runat="server" Text="ASPX:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtaspx_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
</form>
</body>
</html>
And the Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class DateTimeOutput : System.Web.UI.Page
{
protected void output(String value)
{
outputText.Text += value + Environment.NewLine;
}
protected void runButton_Click(object sender, EventArgs e)
{
DateTime dt = new DateTime();
output(dt.ToString());
DateTime nowDt = DateTime.Now;
output(nowDt.ToString());
}
protected void clearButton_Click(object sender, EventArgs e)
{
outputText.Text = "";
}
protected void dt_showSource_btn_Click(object sender, EventArgs e)
{
if (dtcb_output.Visible == false)
{
dtLabel1.Visible = true;
dtcb_output.Visible = true;
}
else
{
dtLabel1.Visible = false;
dtcb_output.Visible = false;
}
if (dtaspx_output.Visible == false)
{
dtLabel2.Visible = true;
dtaspx_output.Visible = true;
}
else
{
dtLabel2.Visible = false;
dtaspx_output.Visible = false;
}
}
}
}
For now source highlighting is not needed, unless its easy to do.
Thx in advance.
If you're refering to the actual code of your code behind file, you have a problem. As the file will be compiled and then be placed as intermediate code in a dynamic link library (.dll), you don't have access to the .aspx.cs file any more. The only way to go would be to include the code behind file with the deployd project and open it with a FileStream (or whatever) to read it and display it's content.

Categories

Resources