Preserving Textbox.Text in a foreach loop

S

Steve

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
 
N

Nathan Sokalski

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.
 
S

Steve

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

Nathan Sokalski said:
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
(e-mail address removed)
http://www.nathansokalski.com/

Steve said:
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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top