In this article I will explain with an example, how to implement automatically scroll to bottom functionality in ASP.Net
Multiline TextBox (TextArea) when Page Loads using
JavaScript.
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing the text.
Button – For adding the TextBox text to the Multiline TextBox i.e. TextArea.
The Button has been assigned with an OnClick event handler.
TextArea – For capturing the text entered in the TextBox.
<asp:TextBox ID="txtSample" runat="server" Text="Sample Text"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="OnAdd" />
<hr />
<asp:TextBox ID="textBox" runat="server" TextMode="MultiLine" Height="100"></asp:TextBox>
Automatically Scroll to Bottom when Page Loads using JavaScript
Inside the window.onload event handler, first the Multiline TextBox i.e. TextArea element is referenced using its ClientID.
Then, its scrollTop position is set to its height using scrollHeight property, which enforces the scroll bar of Multiline TextBox i.e. TextArea to scroll to the bottom.
<script type="text/javascript">
window.onload = function () {
var textarea = document.getElementById('<%=textBox.ClientID %>');
textarea.scrollTop = textarea.scrollHeight;
}
</script>
Adding lines to Multiline TextBox using C# and VB.Net
When Add button is clicked, the text from the TextBox is captured and set to the Multiline TextBox i.e. TextArea.
C#
protected void OnAdd(object sender, EventArgs e)
{
textBox.Text += txtSample.Text + "\n";
}
VB.Net
Protected Sub OnAdd(ByVal sender As Object, ByVal e As EventArgs)
textBox.Text += txtSample.Text & vbLf
End Sub
Screenshot
Demo
Downloads