简体   繁体   中英

ASP.net - How to reference a text box in the code behind?

This is highly likely to be a stupid question, so my apologies. But I can't seem to find an answer anywhere. I am brand new to ASP.net and I'm using C# for the code behind (I have experience with C# from a WinForms project I did, also in Visual Studio)

I have a page, a register for an account page, on the website and I want to be able to access the TextBox that contains email and password etc. I thought it would be something like textboxname.getText() or similar to get what the user has typed into that box when they press submit (clicking submit is my Event ) but I don't now how to make it recognize that textboxname is the ID.

For example:

<input type="email" class="form-control" placeholder="Enter Email" id="email"/>

My email TextBox has an ID of 'email'. In code, if I try to type email.getText() , it does not recognize that email refers to that TextBox . If I could even get it to recognize the ID, I could figure out the rest from there.

Thank you for listening to my excessive beginner ranting! If any extra details are necessary I'll add them, just ask.

Resolved! - For some reason it did not generate a designer for my pages when i created the web forms, so i regenerated the design.cs and it is working! :D Thanks for help anyway!

Be sure your markup is correct on front end - even if you are a space off between quotes it can mess things up.

<asp:TextBox id="email" runat="server" Text="Email" />


email.Text = "your text here";

You should use email.Text; (since it's a property, no a method) instead of email.getText(). Also make sure your control has runat property equals to "server" on HTML.

On your page

you have to declare a form with a submit button and within this form you can have your textbox.

<form id="myForm" runat="server">
    <asp:TextBox id="TB_Email" placeholder="Enter Email" runat="server"></asp:TextBox>
    <asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="Btn_Submit_Click" />
</form>

Code behind

protected void Btn_Submit_Click(object sender, EventArgs e)
{
    // here you can access the value of your email-textbox
    String email = TB_Email.Text;
}

Use:

 <input type="email" class="form-control" placeholder="Enter Email" id="email" runat="server"/>

or alternatively,

<asp:TextBox id="email" runat="server"/> /*Add any other attributes you need*/

In the code behind:

email.Text="your text here";

Without runat="server" attribute, your control is just a HTML control and hence you cannot access it from the server side code(code behind).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM