Preserving Textbox.Text in a foreach loop

  • Thread starter Thread starter Steve
  • Start date Start date
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
 
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,

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
 
Back
Top