Get a Windows Forms control by name in C#
Use the Control.ControlCollection.Find method.
Try this:
this.Controls.Find()
Find control by name from Windows Forms controls
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
Find a control in Windows Forms by name
You can use the form's Controls.Find() method to retrieve a reference back:
var matches = this.Controls.Find("button2", true);
Beware that this returns an array, the Name property of a control can be ambiguous, there is no mechanism that ensures that a control has a unique name. You'll have to enforce that yourself.
Get all controls with names that start with specific string
You can use Linq's where method:
foreach (Label l in this.Controls.OfType<Label>().Where(l => l.Name.StartsWith("tafel_noemer_")))
{
l.Text = "bla bla";
}
Find a specific control by name and modify its .Value property
Assuming that your progressbar control is named "test" (all lowercase letters) and is placed directly on the surface of your form (not inside a groupbox,panel or other control container) then this code should work and simplify your work
foreach (var c in this.Controls.OfType<ProgressBar>().Where(x => x.Name == "test")
{
c.Value = 23;
}
instead if the ProgressBar is placed inside a control container (like a panel) the above code should be changed to loop over the controls collection of the container
foreach (var c in this.panel1.Controls.OfType<ProgressBar>().Where(x => x.Name == "test")
{
c.Value = 23;
}
As pointed out in the comment by KingKing, if you are absolutely sure that a control named "test" exists in your groupbox then a simple lookup in the controls collection should result in your progressbar. Looping is not necessary in this case
ProgressBar pb = this.groupBox1.Controls["test"] as ProgressBar;
if(pb != null) pb.Value = 23;
Getting textbox data from a name C# Windows form
You can use Controls.Find() like this:
string ctlToFind = "textbox00";
TextBox tb = Controls.Find(ctlToFind, true).FirstOrDefault() as TextBox;
if (tb != null)
{
Console.WriteLine(tb.Text);
}
c# group controls by name
You could use the Tag property on the controls which can store any object. Your code would then be:
foreach (Control control in form.Controls)
{
if(control.Tag != null && control.Tag.ToString() == "myTag")
{
//...
}
}
Alternatively, you could use System.Linq to omit the inner if clause:
foreach (Control in form.Controls.Cast<Control>().Where(c => c.Tag != null && c.Tag.ToString() == "myTag"))
{
//...
}
Get name of focused control on the Form
Lets say you have 3 comboboxes on your form and a label.
Add the code for a combobox enter event.
And in this code you will use the sender to get the name of the combobox and display it in the label.
private void CBox_Enter(object sender, EventArgs e)
{
Control CBox = (Control)sender;
label1.Text = CBox.Name;
}
Then you need to select all the comboboxes you want to use, to add CBox_Enter to all the comboboxes enter event.
How to know in a Form what Button was clicked in a UserControl
Consider this simple UserControl:
You have 3 Buttons and 3 TextBox Controls used to input some values:
The 3 Buttons are named btnAddTask1
, btnAddTask2
and btnAddTask3
.
The 3 TextBoxes are named txtTaskName
, txtInput2a
and txtInput2b
.
In the designer, select all 3 Buttons and, in the PropertyGrid, assign a Click
event handler, the same for all Buttons. Give it a name that makes sense (here, the handler is named btnActionTasks
)
Add a public Custom event:
public event EventHandler<ActionTaskEventArgs> ActionTaskClicked;
Where ActionTaskEventArgs
is a custom class derived from EventArgs
, which will return some values when the event is raised, clicking one of the Buttons (see in code).
When one of the Buttons is clicked, you raise the event, passing in the custom EventArgs
some values related to the current Input of the TextBoxes (or whatever else you need).
The sender
object is set to this
, the UserControl's instance, since you may have more than one UserControl of this type in your UI.
One of the custom EventArgs
properties is set to the name of the Button Control that raised the event; other values are also passed to the subscribers of the event (here, taken from the TextBoxes).
In your Form, after you have dropped an UserControl from the ToolBox, subscribe to its public ActionTaskClicked
event as usual, using the PropertyGrid, or manually, as you prefer.
When the event is raised, because an User clicked a Button, you are notified and you can read the value passed in the event arguments as usual:
public partial class UCButtonActions : UserControl
{
public event EventHandler<ActionTaskEventArgs> ActionTaskClicked;
public UCButtonActions() => InitializeComponent();
private void btnActionTasks_Click(object sender, EventArgs e)
{
string buttonName = (sender as Control).Name;
// Or use the Text, the Tag or whatever other value
// string buttonTag = (sender as Control).Tag;
if (int.TryParse(txtInput2b.Text, out int value)){
var args = new ActionTaskEventArgs(buttonName, value, txtInput2a.Text);
ActionTaskClicked?.Invoke(this, args);
}
}
public class ActionTaskEventArgs : EventArgs
{
public ActionTaskEventArgs(string taskName, int value, string svalue)
{
TaskName = taskName;
TaskNumericValue = value;
TaskStringValue = svalue;
}
public string TaskName { get; }
public int TaskNumericValue { get; }
public string TaskStringValue { get; }
}
}
In the Form class, the event handler returns some values in the UserControl's ActionTaskEventArgs
:
private void ucButtonActions1_ActionTaskClicked(object sender, UCButtonActions.ActionTaskEventArgs e)
{
string message = $"You clicked: {e.TaskName}\r\n"+
$"The String Value is: {e.TaskStringValue}\r\n"+
$"The Numeric Value is: {e.TaskNumericValue}\r\n";
MessageBox.Show(message);
}
This is how it works:
Related Topics
How to Replace Multiple Spaces With a Single Space in C#
Selenium C# Webdriver: Wait Until Element Is Present
Data Binding to Selecteditem in a Wpf Treeview
.Net Global Exception Handler in Console Application
How to Remove Duplicates from a C# Array
Filtering Datagridview Without Changing Datasource
How to Update an Observablecollection Via a Worker Thread
Pass Array Parameter in Sqlcommand
Splash Screen Waiting Until Thread Finishes
How to Load Image to Wpf in Runtime
Hresult: 0X800A03Ec on Worksheet.Range
How to Get Output from a Command to Appear in a Control on a Form in Real-Time
Why Is Dictionary Preferred Over Hashtable in C#
Is It Better to Return Null or Empty Collection
What's the Main Difference Between Int.Parse() and Convert.Toint32