Reputation:
Basically a button's tag property is the name of an existing combobox which I need to dynamically reference. It's a generic function to handle multiple buttons. Help
private void SQLButton(object sender, EventArgs e)
{
magic(((Button)sender).Tag.ToString());
}
private void magic(string currentcombo)
{
string CurrentText = (ComboBox).(currentcombo).Text;
}
Upvotes: 2
Views: 9763
Reputation: 50215
You can set the Tag property to the actual ComboBox and avoid your problem altogether.
//code when defining your button...
{
sqlButton.Tag = comboBoxA; //instead of comboBoxA.Name
}
private void SQLButton(object sender, EventArgs e)
{
Button button = sender as Button;
ComboBox comboBox = button.Tag as ComboBox;
if (comboBox == null )
{...}
else
{
magic(comboBox);
}
}
private void magic(ComboBox currentcombo)
{
string CurrentText = currentcombo.Text;
}
Upvotes: 6
Reputation: 24515
Have a look at the Controls.Find Method, to get the instance of the Control using the name.
Upvotes: 1
Reputation: 13719
If currentcombo paramter in magic function is the identifier for the control you are going to change then use Page's function FindControl:
string CurrentText = ((ComboBox)FindControl(currentcombo)).Text;
Page.FindControl() method searches the page naming container for a server control with the specified identifier.
Upvotes: 0
Reputation: 33476
I don't know if its winforms or asp.net. I am assuming it to be winforms
You could use this.Controls(theNameofTheControl)
instead of magic.
Upvotes: 1
Reputation: 564333
I think I understand what you're after -
You'll want to change your "magic" routine to something like:
private void magic(string currentCombo) {
ComboBox box = this.Controls.Find(currentCombo) as ComboBox;
if(box != null) {
// You can do your "work" here...
string currentText = box.Text;
}
}
Upvotes: 4
Reputation: 19407
If you have the string id value of a control then you can use FindControl to get a reference to the control.
Something like ...
Button btn = (Button)FindControl("some_id");
Upvotes: 2