Click here to Skip to main content
16,016,178 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a project that has a webform where all I'm trying to do is set the text of a label to test to make sure the environment works, but the code behind doesn't seem to run at all.

The page is very simple:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="VijilconDefender.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        Hi there<br />
            <br />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>


With only this code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace VijilconDefender
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label Label1 = new Label();
            Label1.Text = "This is a label!";
        }
    }
}


But when I execute, the label is never set.

What I have tried:

I've tried changing from CodeBehind to CodeFile. I've made sure the class reference is the same. I'm not sure why it's not working. It must be my environment, but I have the same problem on localhost, or when I upload to winhost, so that seem to indicate it's a problem with my file. I'm at a total loss of what to try next. Any help is greatly appreciated.
Posted

1 solution

The code-behind is running; it's just not doing what you think it's doing.
Quote:
C#
protected void Page_Load(object sender, EventArgs e)
{
    Label Label1 = new Label();
    Label1.Text = "This is a label!";
}
That creates a brand new Label instance; sets its text to This is a label!; then throws it away, and never looks at it again.

Meanwhile, the Label defined in markup is never mentioned.

Change your code so that it uses the Label1 field, rather than creating a local variable with the same name.
C#
protected void Page_Load(object sender, EventArgs e)
{
    Label1.Text = "This is a label!";
}

NB: WebForms is an ancient and long-dead technology. It sounds like you're starting a new project, which means you should be using a more modern framework - probably ASP.NET Core[^], using MVC, Razor Pages, or Blazor.
 
Share this answer
 
Comments
Matt Schwartz 2024 11hrs ago    
Thank you! That did it! I appreciate your help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900