-1

I have loaded a new page in Web application (webform) using c#. I added a text box and a button to the Design. I double clicked the Button and in the aspx.cs page I added the following:

 protected void Button1_Click(object sender, EventArgs e)
    {
        string name = "Tom";
        MessageBox.Show("My name is " + name);

    }

This, as far as I know, should add text "My name is Tom" inside the Button. But I do not see this reflected in the design (Button is all that is displayed in the button) nor in the html (which makes sense if the new text is not seen in the design).

<body>
<form id="form1" runat="server">
<div>

</div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>

Why is the .cs file not reflected in the html file?

Thank You Tom

miner_tom
  • 177
  • 1
  • 1
  • 13
  • 1
    >>This, as far as I know, should add text "My name is Tom" inside the Button. This won't do this. Code-behind won't update markup. So, you don't get your text in the Designer. Plus, MessageBox.Show is server code. Your users won't see it in their browsers. – Gosha_Fighten Jan 30 '16 at 23:41
  • @Gosha_Fighten you made a little mistake. You are right, that MessageBox will not update the text of button, but you are wrong saying that code behind won't update markup. – Khazratbek Jan 31 '16 at 08:27
  • @miner_tom If you want to update the text of your button, just use following code in your Button1_Click method: Button1.Text = "My name is " + name; And you will see that your button's text has been changed – Khazratbek Jan 31 '16 at 08:28

1 Answers1

1

To put the text next to the button use a literal control:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Literal ID="litMessage" runat="server" />

Then in code:

protected void Button1_Click(object sender, EventArgs e)
{
    string name = "Tom";
    litMessage.Text = "My name is " + name;
}

The message will only show when running, after the click event has happened.


As an aside, MessageBox is something used in windows forms apps (i.e. applications). If you want to display a pop up messagebox to a user on website you need to use JavaScript.

Community
  • 1
  • 1
NikolaiDante
  • 18,469
  • 14
  • 77
  • 117