c# arrays  
Author Message
jbook





PostPosted: Visual C# General, c# arrays Top

here's what i have:

int[] num = new int[ 6 ];

if (numRadioButton.Checked)

{

for (int i = 0; i < 3; i++)

{

num[ i ] = randomGen.Next(0, 9);

}

textBox1.Text = num[0].ToString();

textBox2.Text = num[1].ToString();

textBox3.Text = num[2].ToString();

what i want to do is add the textbox.text to the loop. like somehow put something like this in the loop:

textbox[i + 1].text = num[].tostring()

 i just don't know the right syntax, or do i need a helper method. basically i don't want the three lines of textbox.text code. is there anyway to shorten this




Visual C#3  
 
 
cverdon





PostPosted: Visual C# General, c# arrays Top

Hi,

There is no special syntax to do something like that. You can place the textboxes in an array however:

TextBox[] textboxes = { textbox1, textbox2, textbox3,

textbox4, textbox5, textbox6 };

int[] num = new int[ 6 ];

if ( numRadioButton.Checked ) {

for ( int i = 0 ; i < Math.Min(num.Length, textboxes.Length) ; i++ )
{

num[ i ] = randomGen.Next( 0, 9 );

textboxes[ i ].Text = num[ i ].ToString();

}

}

regards,
Charles


 
 
ahmedilyas





PostPosted: Visual C# General, c# arrays Top

alternatively, you dont need to create an array of textboxes. you can just create 1 on the fly and change its name to a unique name and add it into the container/collection

int[] num = new int[ 6 ];

if (numRadioButton.Checked)

{

   for (int counter=0; counter < num.Length, counter++)

   {

      Random r = new Random();

      int numberChosen = r.Next(0, 9);

      num[counter] = numberChosen;

      TextBox t = new TextBox();

      t.Name = "txt" + counter.ToString();

      t.Text = numberChosen;

      this.Controls.Add(t);

   }

}