Preserving Textbox.Text in a foreach loop

Discussion in 'ASP .Net' started by Steve, Aug 16, 2008.

  1. Steve

    Steve Guest

    I'm trying to populate a TextBox with system drive information. Using the
    following code loops through all of the drives correctly, but only the last
    loop's data shows up in the text box.

    DriveInfo[] allDrives = DriveInfo.GetDrives();

    foreach (DriveInfo d in allDrives)
    {
    TextBox1.Text = "Drive : " + d.Name + "\r\n";
    TextBox1.Text += "File type: " + d.DriveType + "\r\n";
    }

    Is there some way that I can preserve the data each time? The Textbox is
    declared in the deafult.aspx.designer.cs window as

    protected global::System.Web.UI.WebControls.TextBox TextBox1;

    I know this is simple, but I am just not seeing it.

    Thanks,

    Steve
     
    Steve, Aug 16, 2008
    #1
    1. Advertisements

  2. Your problem is that you are setting the Text property in the first line in
    the foreach rather than appending to it. Change your code to the following:

    TextBox1.Text="";
    foreach (DriveInfo d in allDrives)
    {
    TextBox1.Text += "Drive : " + d.Name + "\r\n";
    TextBox1.Text += "File type: " + d.DriveType + "\r\n";
    }

    This will insure that the Text property is empty when you start adding to
    it, and it is always appended to rather than set. Hopefully this helps.
     
    Nathan Sokalski, Aug 17, 2008
    #2
    1. Advertisements

  3. Steve

    Steve Guest

    Nathan,

    Thanks very much for catching that. I must have looked at that line a dozen
    times, but just didn't spot it. I feel like such a newbie... ;-)

    Cheers,

    Steve

     
    Steve, Aug 17, 2008
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.