For some of you, this may seem trivial - but please indulge me as I seem to have a severe mental block in understanding how displaying array elements is possible.
Ok, so here's where I'm at:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestCoding._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Modify this template to jump-start your ASP.NET application.</h2>
</hgroup>
<p>
<asp:TextBox ID="post_feedback" runat="server" Height="100" Width="500" BackColor="#0066FF" Font-Bold="True" ForeColor="#FF9933" Wrap="False" TextMode="MultiLine" BorderColor="#000099" BorderStyle="Groove" BorderWidth="2"></asp:TextBox>
<br />
<asp:Button ID="Count_Sentences" runat="server" Text="Count Sentences" OnClick="Count_Sentences_Click"/>
<br />
<br />
<asp:Label ID="Num_Sentences" runat="server" Font-Bold="true">How Many Sentences Do we have today?</asp:Label>
</p>
</div>
</section>
</asp:Content>
And the Default.aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestCoding
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Count_Sentences_Click(object sender, EventArgs e)
{
int post_length = post_feedback.Text.Length;
string[] post_words = post_feedback.Text.Split(' ');
int num_words = post_words.Length;
Num_Sentences.Text = post_feedback.Text + " " + Convert.ToString(post_length) + " and has " + post_words.Length + " words." + post_words[0];
for (int i = 0; i < num_words; i++)
{
Console.WriteLine(post_words[i]);
}
}
}
}
Ok, so I understand that Num_Sentences is a Label I created in the aspx page - and that on clicking the button, the Count_Sentences_Click routine is called, it does some "stuff" and binds Num_Sentences.Text to a string that's comprised of different strings and other data...
The bit of code after that data binding, which I intend to have all the elements in the post_words array be written...but it's not working out so well.
What I have found so far it seems is, "Oh, all you have to do is set up a loop of sorts and just do Console.WriteLine(arrayname[i]) and all will be well with the universe."
Obviously, I am having some problems in understanding how to successfully display the array elements. Do I need a separate Label ID to put this into or what? I'm confused. :P
Related
here is my ASPX code
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
function sum(t1)
{
var txt1 = document.getElementById('MainContent_TextBox2').value;
var result = parseInt(txt1) / 2;
var result1 = parseInt(result);
if (!isNaN(result))
{
document.getElementById(t1).value = result1;
}
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBox2" runat="server" onkeyup="sum('MainContent_TextBox3')"</asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
and my c# code is that
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox4.Text = TextBox3.Text;
}
}
the problem is that when i click on Button1 no error and TextBox4 is empty and i want that when i click on Button1 textbox3 value is transfered in textbox4.
It's because of the ReadOnly="True" that you have set on TextBox3.
When a control is set to ReadOnly in ASP.NET, the value that was placed into the control when the page was original rendered will not be updated.
Even if you change the value in the control on the browser (as you are doing), the value that is sent back to the server will not effect the value in the TextBox control - it will keep it's old value thanks to the ViewState.
The answer is to store the new value in a <asp:HiddenField>, which you should update at the same time as TextBox3.
Then on the server use the value in the hidden field, as that will contain the value you want. (Also, remember that you will need to update the value in the textbox from the hidden control as part of the postback).
I have peice of code in ASP.Net for execute code of C# using roslyn compiler. However, I use ASP.Net web forms to build user interface for execute the code. So,I want to take code from one textbox and by "Compile" button I show the result in another textbox.
So, I have this controls:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Compiler Tool</h1>
</hgroup>
<p>
You can compile your source code of C# using Roslyn Compiler from Microsoft</p>
<br/>
<p>
<asp:TextBox ID="TextBox3" runat="server" Height="185px" Width="480px" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button2" runat="server" onclick="Button_Click" Text="Compile" ForeColor="Black" />
</p>
<p>
<asp:TextBox ID="TextBox2" runat="server" Height="138px" Width="390px" ></asp:TextBox>
</p>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
</asp:Content>
And here the Handler event for it using C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
var engine = new ScriptEngine();
var session = engine.CreateSession();
String code = TextBox3.Text;
session.Execute(code);
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
}
}
How could I show the result of execution of Code (TextBox3) in TextBox2??
Iam beginner in ASP.Net environment, Any help??
I'm afraid I'm not near a dev pc, so I can't test the code, but here's what comes to mind:
You're not using the result of session.Execute(code);, so if a user were to put in 3+3, it would get executed, and the return value would be 6, but since it's not captured, it simply would go out of scope. If instead, you did object result = session.Execute(code);, the output would be the integer 6; You could then call .ToString() on result and put that in your text box.
And of course be careful allowing users to execute arbitrary code on your webserver...
I am working on a simple asp.net login page. Yesterday, the code was working fine. Today, it isn't.
The only thing that changed between yesterday and today is that I shut down my pc and started it again today.
The problem is that Page_Load is firing twice (I checked all the answers/solutions, and none worked (image with empty src, handling the page_load manually, setting autoEventWireUp to false...)) none of these seemed to do the trick.
PLEASE can someone help me figure out why this is happening?
Here is the code for the page and its code behind:
<%# Page Title="Login" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="Login.aspx.cs" Inherits="MatchingWebsite.Login" MaintainScrollPositionOnPostback="true" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %></h1>
</hgroup>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2 align="center">Looking for someone to spend your time with? Want to have fun with someone you like?<br />You've come to the right place!!</h2><br /><br /><br />
<img alt="Cupid" src="Images/images.jpg" align="left" />
<img alt="Couple" align="right" src="Images/matchmaking.jpg" /><br /><br />
Username:<br />
<asp:TextBox ID="UserLogIn" runat="server" Width="174px"></asp:TextBox><br /><br />
Password:<br />
<asp:TextBox ID="UserPass" runat="server" Width="175px" TextMode="Password"></asp:TextBox><br />
<asp:Label ID="LoginError" runat="server" Text="Wrong Username/Password Combination. Try again." Visible="False"></asp:Label><br /><br />
<asp:Button ID="LoginButton" runat="server" OnClick="Login_Click" Text="Login" Width="81px" />
<asp:Button ID="NotRegistered" runat="server" Text="Not Registered?" Width="150px" OnClick="Not_Registered" />
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.auto-style1
{
width: 300px;
height: 113px;
}
</style>
</asp:Content>
And here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MatchingWebsite
{
public partial class Login : System.Web.UI.Page
{
Service1 proxy = new Service1();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"]!=null && !IsPostBack)
Response.Redirect("~/EnterMyInfo.aspx");
}
protected void Login_Click(object sender, EventArgs e)
{
string user = UserLogIn.Text;
string pass = UserPass.Text;
if (user == "" || pass == "")
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\"Username/Password cannot be blank.\")</SCRIPT>");
else
{
if (proxy.login_service(user, pass))
{
Response.Redirect("~/EnterMyInfo.aspx");
}
else
LoginError.Visible = true;
}
}
protected void Not_Registered(object sender, EventArgs e)
{
Response.Redirect("~/SignUp.aspx");
}
}
}
Likely the webpage is really loaded twice. Check your javascripts (or any AJAX components?), or use the browser's debug console to monitor the network requests being sent. Try adding empty methods on the PreInit, PostInit (etc.) events and set breakpoints too, I bet those are hit twice as well.
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.
I code a example like telerik Upload demo but have the following error when submit(in FF):
The connection was reset.
The demo of telerik RadUpload is here
This is the code of .aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage1.master" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Main_Upload" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<title>Upload file</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<telerik:RadScriptManager ID="rsmScriptManager" runat="server">
</telerik:RadScriptManager>
<telerik:RadProgressManager ID="rpmUploadFile" runat="server" />
<div style=" color:Green">Valid files(*.doc, *.docx, *.xls, *.xlsx, *.pdf)</div>
<telerik:RadUpload ID="rulFiles" runat="server" InitialFileInputsCount="2" MaxFileInputsCount="5" AllowedFileExtensions=".doc,.docx,.xls,.xlsx,.pdf">
</telerik:RadUpload>
<telerik:RadProgressArea runat="server" ID="rpaUpload"></telerik:RadProgressArea>
<asp:Button ID="btnUpload" runat="server" Text="Ok" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblNoResults" runat="server" Visible="True">No uploaded file!</asp:Label>
<asp:Repeater ID="rptValidResults" runat="server" Visible="false">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
</ItemTemplate>
</asp:Repeater>
<div style="color: red; padding-top: 40px;">Invalid files:</div>
<asp:Label id="lblNoInvalidResults" runat="server" Visible="True">No invalid files.</asp:Label>
<asp:Repeater ID="rptInvalidResults" runat="server" Visible="false">
<ItemTemplate>
File: <%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
Mime-type: <%#DataBinder.Eval(Container.DataItem,"ContentType") %>
</ItemTemplate>
</asp:Repeater>
And the code behind in *.cs file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
public partial class Main_Upload : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
BindValidResult();
BindInvalidResult();
}
private void BindValidResult()
{
if(rulFiles.UploadedFiles.Count > 0)
{
foreach (UploadedFile validFile in rulFiles.UploadedFiles)
{
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
validFile.SaveAs(Path.Combine(targetFolder,validFile.GetName()),true);
}
lblNoResults.Visible = false;
rptValidResults.Visible = true;
rptValidResults.DataSource = rulFiles.UploadedFiles;
rptValidResults.DataBind();
}
else
{
lblNoResults.Visible = true;
rptValidResults.Visible = false;
}
}
private void BindInvalidResult()
{
if(rulFiles.InvalidFiles.Count > 0)
{
lblNoInvalidResults.Visible = false;
rptInvalidResults.Visible = true;
rptInvalidResults.DataSource = rulFiles.InvalidFiles;
rptInvalidResults.DataBind();
}
else
{
lblNoInvalidResults.Visible = true;
rptInvalidResults.Visible = false;
}
}
}
Thanks!!!!
I'll go ahead and tell you with almost 100% certainty that the line that is causing this is:
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
It could be that you do not have permission to connect the server, or a variety of other issues.
To test this change "var targetFolder" to something like:
var targetFolder = #"C:\Users\j\Desktop\TEMP\"
Run this and it works perfectly, hence the idea that the path you're trying to access on the server is the problem.
Perhaps you should specify the path if possible. For example, if you are on a domain:
var targetFolder = #"\\server\Users\"
This would access that server and then the users folder therein that I have on my domain.