Load a txt file in a TextBox

Here is a very simple piece of C# code to load a text file in a TextBox. Typical use to display a disclaimer

[Update 1: added using statement for the StreamReader]

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        using (StreamReader StreamReader1 =
            new StreamReader(Server.MapPath("disclaimer.txt")))
        {
            txtDisclaimer.Text = StreamReader1.ReadToEnd();
            StreamReader1.Close();
        }
    }
}

[Update 2: use the new File.ReadAllText() wrapper for StreamReader, exact same thing, but 1 line of code instead of 3...]

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtDisclaimer.Text =
File.ReadAllText(Server.MapPath("disclaimer.txt")); } }

FYI here is the static ReadAllText method in Reflector:

Then you could add a CheckBox to enable a Postback Button (disabled by default):

<input id="cbAgree" type="checkbox" onclick="ManageBtnGoState();" />
<label for="cbAgree" style="font-weight:bold; color:Red;">
I Agree with the present statement</label>
<asp:Button ID="btnGo" runat="server" Text="Take Survey"
onclick="btnGo_Click" Enabled="false" />

And the Js function:

<script type="text/javascript">
function ManageBtnGoState()
{
    $get('<%= btnGo.ClientID %>').disabled = 'disabled';  
    if ( $get("cbAgree").checked == true )
    {    $get('<%= btnGo.ClientID %>').disabled = '';  }
}
</script>

Note that $get() is a function from the ASP.NET AJAX client framework. If you don't have it please use document.getElementById() instead.

 

Another solution

Load the txt file from Resource.

First add the text file as Resource in a resx file of your project (here common.resx):

 

You can event have one file per language!


Then the code looks like:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtDisclaimer.Text = Resources.Common.disclaimer_en;
    }
}

You could add a check for the current culture and load the corresponding disclaimer file.

Published Sunday, March 02, 2008 11:51 PM by pluginbaby
Filed under:

Comments

Sunday, March 02, 2008 8:43 PM by Gauthier Segay

# re: Load a txt file in a TextBox

Since StreamReader implements IDisposable, it couldn't be bad to use using statement in your server code.

Sunday, March 02, 2008 9:22 PM by John S.

# re: Load a txt file in a TextBox

I like File.ReadAllText(path) instead of having to deal with StreamReaders. For example:

txtDisclaimer.Text = File.ReadAllText(Server.MapPath("disclaimer.txt"));

Tuesday, March 04, 2008 3:28 PM by rascunho » Blog Archive » links for 2008-03-04

# rascunho &raquo; Blog Archive &raquo; links for 2008-03-04

Pingback from  rascunho  &raquo; Blog Archive   &raquo; links for 2008-03-04