Sir/Ma'am
I have a groupbox that contains several textboxes. I'm trying to select a random number of said textboxes and change their backcolor to green. I was able to determine how to iterate through the entire groupbox to change the backcolor of all the textboxes (below), but now I would like to learn how to just change a random number of textboxes backcolor. Specifically, can I change some (i.e. random) of the textboxes backcolor within a specific groupbox?
As always, I appreciate your assistance with my learning endeavors…
private void button5_Click(object sender, EventArgs e)
{
groupBox46.BackColor = Color.White;
foreach (Control Text in groupBox46.Controls)
{
Text.BackColor = Color.Green;
}
}
}
}
FroglegPosted Apr 3, 2011, 8:08 PM
public partial class Form1 : Form
{
int[] index ;
int textCount = 0,textChoice = 0;
Random random1 = new Random();
Random random = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
textCount = 0;
textChoice = 0;
clearBoxes();
textChoice = random1.Next(1, textCount);
index = new int[textChoice];
for (int i = 0; i < index.Length; i++)
{
index[i] = 0;
}
int j;
for (int i = 0; i < index.Length; i++)
{
j = getRandom();
index[i] = j;
}
Array.Sort(index);
int count = 0,listCount = 0;
foreach (Control tb in groupBox1.Controls)
{
if (tb is TextBox)
{
if (listCount > index.Length - 1)
{
break;
}
if (count == index[listCount])
{
tb.BackColor = Color.Green;
listCount++;
}
count++;
}
}
}
public int getRandom()
{
int i = random.Next(1, textCount);
if (index.Contains(i))
{
i = getRandom();
}
return i;
}
public void clearBoxes()
{
foreach (Control tb in groupBox1.Controls)
{
if (tb is TextBox)
{
tb.BackColor = Color.White;
textCount++;
}
}
}
}
}
matthew kingPosted Apr 3, 2011, 7:31 PM
FroglegPosted Apr 3, 2011, 7:27 PM
So 1 to 300 textboxes
we still need to know how many of the 300 to change the backcolor of
matthew kingPosted Apr 3, 2011, 6:49 PM
The user will imput the number...it will be between 10 and 300... So, the random number will be somewhere in that range.
FroglegPosted Apr 3, 2011, 6:44 PM
groupbox has 6 textboxes. Change any three to a different backcolor