How do I set an ASP.NET Label text from code behind on page load?

前端 未结 7 1698
终归单人心
终归单人心 2020-12-03 07:39

I can\'t seem to find an answer out there for this. Here\'s the scenario: I have an ASP.NET project using C#. I\'m loading data (Username, email, etc...) from a sqlite datab

相关标签:
7条回答
  • 2020-12-03 07:45

    For this label:

    <asp:label id="myLabel" runat="server" />
    

    In the code behind use (C#):

    myLabel.Text = "my text"; 
    

    Update (following updated question):

    You do not need to use FindControl - that whole line is superfluous:

      Label myLabel = this.FindControl("myLabel") as Label;
      myLabel.Text = "my text";
    

    Should be just:

      myLabel.Text = "my text";
    

    The Visual Studio designer should create a file with all the server side controls already added properly to the class (in a RankPage.aspx.designer.cs file, by default).

    You are talking about a RankPage.cs file - the way Visual Studio would have named it is RankPage.aspx.cs. How are you linking these files together?

    0 讨论(0)
  • 2020-12-03 07:49
    protected void Page_Load(object sender, EventArgs e)
    {
        myLabel.Text = "My text";
    }
    

    this is the base of ASP.Net, thinking in controls, not html flow.

    Consider following a course, or reading a beginner book... and first, forget what you did in php :)

    0 讨论(0)
  • 2020-12-03 07:51

    In the page load event you set your label

    lbl_username.text = "some text";

    0 讨论(0)
  • 2020-12-03 07:53

    Try something like this in your aspx page

    <asp:Label ID="myLabel" runat="server"></asp:Label>
    

    and then in your codebehind you can just do

    myLabel.Text = "My Label";
    
    0 讨论(0)
  • 2020-12-03 08:07

    In your ASP.NET page:

    <asp:Label ID="UserNameLabel" runat="server" />
    

    In your code behind (assuming you're using C#):

    function Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           UserNameLabel.Text = "User Name";
        }
    }
    
    0 讨论(0)
  • 2020-12-03 08:08

    I know this was posted a long while ago, and it has been marked answered, but to me, the selected answer was not answering the question I thought the user was posing. It seemed to me he was looking for the approach one can take in ASP .Net that corresponds to his inline data binding previously performed in php.

    Here was his php:

    <p>Here is the username: <?php echo GetUserName(); ?></p>
    

    Here is what one would do in ASP .Net:

    <p>Here is the username: <%= GetUserName() %></p>
    
    0 讨论(0)
提交回复
热议问题