I have a form with 7 buttons and 7 comboboxes. When I click one of the buttons, I want to put text into the corresponding combobox, so button number 4 puts text into combobox4.
Simple enough, however, I do not want to have to repeat my code, I want it all in one block, so one chunk handles everything.
I am using FindControl, as we posted many times before in here, and elsewhere, and it works, but you can see from my switch statement, that I am still repeating code. I want to crunch that switch down to a single entry.
I created a function called AddText, it requires a string, and an object in order to work. I can then do a for loop to feed it, but not sure how to get the component for the combobox object to send it. In the switch statement, I simply put the name in there and the backend knows what object I want, but how to do that in a loop?
What I have tried:
namespace LotsButtons
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button aButton = (Button)sender;
string lastchar = aButton.Text.Substring(aButton.Text.Length - 1);
ComboBox cbFound;
string cbName = "comboBox" + lastchar;
switch (lastchar)
{
case "1":
cbFound = (ComboBox)FindControl(cbName, comboBox1);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "2":
cbFound = (ComboBox)FindControl(cbName, comboBox2);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "3":
cbFound = (ComboBox)FindControl(cbName, comboBox3);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "4":
cbFound = (ComboBox)FindControl(cbName, comboBox4);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "5":
cbFound = (ComboBox)FindControl(cbName, comboBox5);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "6":
cbFound = (ComboBox)FindControl(cbName, comboBox6);
if (cbFound != null)
cbFound.Text = "Yay";
break;
case "7":
cbFound = (ComboBox)FindControl(cbName, comboBox7);
if (cbFound != null)
cbFound.Text = "Yay";
break;
}
for (int cnt = 1; cnt < 8; cnt++)
{
AddText(lastchar, (ComboBox)cbName);
}
}
private void AddText(string cbName, ComboBox cbToFind)
{
ComboBox cbFound = (ComboBox)FindControl(cbName, cbToFind);
if (cbFound != null)
cbFound.Text = "Yay";
}
public static Control FindControl(string controlId, Control container)
{
if (container.Name == controlId)
return container;
foreach (Control control in container.Controls)
{
Control c = FindControl(controlId, control);
if (c != null)
return c;
}
return null;
}
}
}