Julián
Julián

Reputation: 1386

How to adapt the size of a Textbox (MultiLine) to a text in ASP .NET C#?

I have an .aspx form and in the Page_Load event I assign several values to controls (Textbox, DropdownList, etc.) from the database, however I have a Textbox control where it is possible that the text is very large or very small, it is here where I would like to know if it is possible to make the textbox size dynamic.

When the form finishes loading the Textbox control it is displayed like this:.

enter image description here

But I would like to visualize it like this (everything depends on the text):

enter image description here

Textbox Code:

<asp:TextBox runat="server" ID="txt" TextMode="MultiLine" Height="80px" ReadOnly="true" CssClass="form-control"></asp:TextBox> 

I am using .NET Framework 4.5.2, I am not sure if I should use any functionality from jQuery and if so, how would it be done?

Upvotes: 0

Views: 2339

Answers (2)

wazz
wazz

Reputation: 5068

You could use a literal control

<asp:Literal ID="Literal1" runat="server"></asp:Literal> 

or an html div with runat="server" added.

<div id="specialDiv" runat="server"></div>

c#

specialDiv.InnerText = "asdfasdf...etc";

Note, if you use CssClass="form-control", you might have to update the css by setting height to auto, instead of the preset/hard-coded height.

Upvotes: 0

Sean T
Sean T

Reputation: 2494

You can do this with Javascript or Jquery on page load quite easily.

Jquery:

$(function(){//executes when dom is ready

    var textAreaAdjust = function(control) {//function to set the height
        $(control).height(1);
        $(control).height($(control).prop('scrollHeight'));
    }

    textAreaAdjust($('#txt'));// call the function passing the textarea control in
});

Javascript:

document.addEventListener("DOMContentLoaded", function () {

        var textAreaAdjust = function(control){//funciton to measure and set height
            control.style.height = "1px";
            control.style.height = (25+control.scrollHeight)+"px";
        };

        var textControl = document.getElementById("txt");//get the textarea
        textAreaAdjust(textControl);//pass it into the function

}​);

Credit to this answer

Upvotes: 1

Related Questions