Jay
Jay

Reputation: 1309

Value and Text properties in asp.net TextBox (Value gets overwritten by Text )

I have TextBox like below.

<asp:TextBox runat="server" ID="Name" value="aaaa" text="bbbb"/>

in code behind.

Dim str As String = Name.Text.Trim() ' value as bbbb

If I removed the text property.

<asp:TextBox runat="server" ID="Name" value="aaaa" /> <%--text="bbbb"--%>    

Dim str As String = Name.Text.Trim() ' value as aaaa

whenever I am keeping text property I am not able to access Value field. How to get the value field when text property is present?

Upvotes: 6

Views: 28040

Answers (3)

Karl Anderson
Karl Anderson

Reputation: 34834

If you are trying to store data associated to a control on the page, then consider using the ASP.NET HiddenField control to store values that can be read across post backs to the server, like this:

<asp:HiddenField runat="server" id="HiddenFieldValue" />

Then in code-behind, you can get and set the value via the Value property, like this:

' Storing value
Me.HiddenFieldValue.Value = "value you want to keep"

' Retrieving value
Dim str As String = Me.HiddenFieldValue.Value

Upvotes: 0

Agustin Meriles
Agustin Meriles

Reputation: 4854

Don't use the value property. If you are using asp.net's TextBox you must use Text.

When you add properties that don't exists in the TextBox class, asp.net will render those properties to the resulting html. So

<asp:TextBox runat="server" ID="Name" text="bbbb" mycustomproperty="hi" />

Will render to something like this

<input type="text" value="bbbb" id="..." name="..." mycustomproperty="hi"/>

If you omit the TextBox's Text property and write the value property, then the value property will be rendered.

<asp:TextBox runat="server" ID="Name" value="aaaa" />

To

<input type="text" value="aaaa" id="..." name="..."/>

TextBox doesn't has a Value property. When the TextBox instance is created, the HTML value property will be assigned to the Text property, and that's why you access the Text property it has the "aaaa" value.

Summary: Don't use value property when you use ASP.NET controls. Use the controls specific properties.

Upvotes: 6

ED-209
ED-209

Reputation: 4746

Value isn't a valid property of an asp:Textbox

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx

Upvotes: 0

Related Questions