I have many buttons and labels on my c# form. I have a button that changes all butons' and labels' text properties (change language button). Do i have to write all items in click event of button or is there a method that scans all form control items and change their text properties.
There are many other controls that contains labels or buttons. For example a label is added to the control of a panel and when i iterate form controls, i can't reach this label. I want to change all items' text properties at one time.
Thank you.
foreach (Control objCtrl in yourFormName.Controls) {
if (objCtrl is Label)
{
// Assign Some Text
}
if (objCtrl is Button)
{
// Assign some text
}
}
If a CS0120 error happens, change yourFormName.Controls to this.Controls;
Assuming ASP.NET's ITextControl Interface (works similar for Winforms-Controls' Text-Property ):
var text = "Hello World";
var allTextControls = this.Controls.OfType<ITextControl>();
foreach(ITextControl txt in allTextControls)
txt.Text = text;
http://msdn.microsoft.com/en-us/library/bb360913.aspx
Edit: You could easily make it an extension(e.g. ASP.NET, for Winforms replace ITextControl with Control):
public static class ControlExtensions
{
public static void SetControlChildText(this Control rootControl, String text, bool recursive)
{
var allChildTextControls = rootControl.Controls.OfType<ITextControl>();
foreach (ITextControl txt in allChildTextControls)
txt.Text = text;
if (recursive) {
foreach (Control child in rootControl.Controls)
child.SetControlChildText(text, true);
}
}
}
Now you can call it for example in this way:
protected void Page_Load(object sender, EventArgs e)
{
Page.SetControlChildText("Hello World", true);
}
This will apply the given text on every child control implementing ITextControl(like Label or TextBox).
If it's winforms you should read about localizing your application here:
Walkthrough: Localizing Windows Forms
I think if you are using javascript, you can simply go through the DOM and modify the texts of the buttons and labels. Using jQuery this will be very simple
For a web application, you could do this quite easily with jQuery. Have a look at this: http://api.jquery.com/category/selectors/
$('label').each(function(){this.value = 'something else';});
For Winforms, you can use this:
foreach (var c in Controls.OfType<TextBox>())
c.Text = "TextBox Text";
foreach (var c in Controls.OfType<Label>())
c.Text = "Label text";
But I agree with #ionden, you should consider localizing your application.
There is a Controls property that contains all controls of your form. You can iterate over it:
foreach(var control in Controls)
{
var button = control as Button;
if(button != null)
button.Text = Translate(button.Text);
else
{
var label = control as Label;
if(label != null)
label .Text = Translate(label .Text);
}
}
foreach( Control ctlparent in this.Controls)
{
if(ctlparent is Panel or ctlparent is GroupBox)
{
foreach(Control ctl in ctlparent.Controls)
{
if(ctl is Label or ctl is Button)
{
ctl.Text= newtext;
}
}}
This will work.
Related
I have tons of Buttons named like this x0y1
How do I access the variable name dynamically so I could loop all names by xiy1 or so.
in PHP it would be like ${"myString" . $randomvar}
I can't use a list or array because the the button already exist defined through the xaml
You can use:
var textbox =
this.Controls.OfType<TextBox>().Where(txb => txb.Name == "myString").FirstOrDefault();
This assumes you are in the context of your form (this.Controls).
And of course, don't forget to add using System.Linq;...
You can get all the textbox using this method
void AllTextBox(System.Windows.Forms.Control.ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
{
if (ctrl.Name == "textBox1")
{
// do your stuf with textbox
}
}
}
}
You can create function that return control by name :
Control GetControlByName(string Name)
{
foreach(Control control in this.Controls)
if(c.Name == Name) return control ;
return null;
}
or Function with a specific control like that :
Button GetButtonByName(string Name)
{
foreach (Control c in this.Controls.OfType<Button>())
if (c.Name == Name) return c;
return null;
}
For wpf project...
Let's say you have a grid named MyGrid and there's lot of buttons on it.
You want to refer to the button named x0y1:
var btn = MyGrid.Children.OfType<Button>().Where(x=>x.Name=="x0y1");
Note: above code should work for flat structure (one level deep only).
You can achieve the same by using code provided in this thread: How can I find WPF controls by name or type?
Just call FindName("elementName"). FindName searches through all child elements of a FrameworkElement. To access any button by its name as string in a window, call the FindName() method of the window !
If your code is in a class inheriting from Window, just use:
Button button = (Button)FindName("xiy1");
If you write the code in a class not inheriting from Window but FrameworkElement, which is unlikely, use:
Window window = Window.GetWindow(this);
Button button = (Button)window.FindName("xiy1");
Check the MSDN documentation about Namescopes for more information about limitations.
I am working on winform application in asp.net using c#. I have 10 labels on my winform created in the designer mode, called Label0 to Label9. Now I want to change the Text property of all the labels at once as per the data I acquire in the middle of execution of my program.
i want to do something like this :
for (int i = 0; i < 10; i++)
{
Label[i].Text = "Hello, this is label: "+ i.ToString();
}
Now, of course this won't work. But how can this be done? how can i call the label like its done in an array? If not possible, then what can be the best alternative solution for my problem?
If you are talking about WinForms, then you can do like this:
private void Form1_Load(object sender, EventArgs e)
{
// Form1_Load is just sample place for code executing
for (int i = 1; i < 10; i++)
{
var label = Find<Label>(this, "label" + i);
label.Text = "Hello, this is label: " + i.ToString();
}
}
private T Find<T>(Control container, string name)
where T : Control
{
foreach (Control control in container.Controls)
{
if (control is T && control.Name == name)
return (T)control;
}
return null;
}
This code will search label in form controls, and then return it based on control name and type T. But it will use just parent form. So if your label is in some panel, then you need to specify panel as container parameter. Otherwise Find method can be updated as recursive method, so it will search inside all form subcontrols, but if there will be two Label1 controls, then it will return just first one, that might be not correct.
If you can put all Label on a panel after the you can use below code to change the text
foreach (Control p in panal.Controls)
if (p.GetType == Label)
p.Text = "your text";
I'm cycling over my WinForms controls and give their Text and ToolTipText to my Translation service for translation.
Example:
foreach (ToolStripItem item in toolStrip.Items)
{
if (item is ToolStripMenuItem)
{
item.ToolTipText = Translate(item.ToolTipText);
item.Text = Translate(item.Text);
}
}
However, I cannot access tooltips set by using the WinForms ToolTip control.
I see I can cycle over the components. Can I Get and Set their tooltips?
protected void TranslateToolTip(ToolTip toolTip)
{
foreach (var component in toolTip.Container.Components)
{
// Doesn't work. No ToolTipText property
component.ToolTipText = Translate(component.ToolTipText);
}
}
Can I access the tooltip text directly from the control?
To set a tooltip text on all components in your form like button1 etc. I think you should use something like this:
foreach (var control in this.Controls) {
ToolTip1.SetToolTip(this.control, "Your text");
}
That's because ToolTip doesn't have a Text property and it's set like on example above.
See also ToolTip Class and ToolTip.SetToolTip Method and ToolTip.GetToolTip Method
Or you can try something like that but not sure if this gonna work:
protected void TranslateToolTip(ToolTip toolTip)
{
foreach (var component in toolTip.Container.Components)
{
// Doesn't work. No ToolTipText property
// component.ToolTipText = Translate(component.ToolTipText);
toolTip.SetToolTip(component , (string)Translate(toolTip.GetToolTip(component));
}
}
I don't know what Translate(component.ToolTipText) is supposed to return. If it's just translated string, then we don't need the (string) part in my exmple.
Hope it helps.
EDIT: Fixed second example to show how to Set and Get tooltip text from specific control.
I'm trying to put dynamicaly a LinkLabel (also I traied to put a button) in a TabPage:
LinkLabel newLinkLabelButton = new LinkLabel();
newLinkLabelButton.Text = "Login";
newLinkLabelButton.Name = "linkLabel_11";
tabs.TabPages[0].Controls.Add(newLinkLabelButton);
Now I'm trying to find this control on the specificf TabPage with function
newLoginLinkLabel = (LinkLabel)Helper.GetLinkLabelByTagAndfamily(tabs.TabPages[0], _name);
where the function body is:
public static Control GetControlByTagAndfamily(TabPage _tab, string _name)
{
Control rez = new Control();
foreach (Control ctrl in _tab.Controls)
{
if (ctrl.Name == _name)
{
rez = ctrl;
break;
}
}
return rez;
}
But the function never founds a LinkLabel or a Button inside _tab.Controls collection. I observed the collection contains founds Labels only, if I trying to find some labels inside.
Pleas help to solve this.
Well, my problem is solved, the code above is correct. The problem was in wrong _name calculation before using it in
GetControlByTagAndfamily(TabPage _tab, string _name);
I have seen many others with similar problems but I cannot find the flaw in my logic here. Any help would be greatly appreciated.
I have a Panel which I have added numerous label and textbox controls to, ie:
myPanel.Controls.Add(txtBox);
These controls are created and added in a method called previous to the iteration method.
I want to iterate through each textbox and use its Text property as a parameter in another method but I am not having any luck. Here is my attempt to iterate:
public void updateQuestions()
{
try
{
foreach (Control c in editQuestionsPanel.Controls)
{
if (c is TextBox)
{
TextBox questionTextBox = (TextBox)c;
string question = questionTextBox.Text;
writeNewQuestionToTblQuestions(question);
}
}
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
The problem I am having is that the controls are not in the Panel when I arrive at this updateQuestions() method. Here is the process involved:
A commandButton is clicked and the questions are read from a DB, for each question a method is called which adds 2 labels and a textbox to editQuestionsPanel.Controls. This panel is inside a PlaceHolder which is then made visible.
When a button inside the PlaceHolder is clicked, the updateQuestions() method is called and the editQuestionsPanel.Controls.Count = 1. As there are approx 12 questions in the DB it should be around 36. The one control inside the Panel is of type:
System.Web.UI.LiteralControl
It contains no controls.
I am sure that somwhere in the lifecycle the Panel's controls are being cleared but I do not know how to step thru the life cycle. I have a Page_load method which is called as soon as a button is clicked but once the button which calls updateQuestions() is clicked the editQuestionsPanel.Controls.Count is already back to 1 so it must be cleared before this but I do not know how to correct this...
Any help you can give to help me solve this would be greatly appreciated - its killing me!
This selects from collection controls only that which are of type TextBox.
(the same as control is TextBox or (control as TextBox) != null)
If controls are contained in editQuestionsPanel.Controls:
using System.Linq;
IEnumerable<TextBox> textBoxes = editQuestionsPanel.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxes)
{
// do stuff
}
To select all child controls use next extension method:
public static IEnumerable<T> GetChildControls<T>(this Control control) where T : Control
{
var children = control.Controls.OfType<T>();
return children.SelectMany(c => GetChildControls<T>(c)).Concat(children);
}
Using:
IEnumerable<TextBox> textBoxes = editQuestionsPanel.GetChildControls<TextBox>();
When you add controls dynamically, you need to do that on every request - asp.net doesn't do that for you!
Add the controls in the Init or Load phase, then they will get populated with the postback values.
A frequently made mistake: Container.Controls only contains the first level child controls in this container. That is: TextBox1 in PanelA, PanelA in PanelB, you can't get TextBox1 in PanelB.Controls.
My solution is to write an extension method:
public static IEnumerable<Control> AllControls(this Control ctl)
{
List<Control> collection = new List<Control>();
if (ctl.HasControls())
{
foreach (Control c in ctl.Controls)
{
collection.Add(c);
collection = collection.Concat(c.AllControls()).ToList();
}
}
return collection;
}
Now TextBox1 is in PanelB.AllControls(). To filter all controls with type, using PanelB.AllControls().OfType<TextBox>()
If the other answers don't help, try doing your code but add recursivity. Your code would not work if it's editQuestionsPanel => Panel => Textbox
You can do something like this instead:
var questions = from tb in editQuestionsPanel.Controls.OfType<TextBox>()
select tb.Text;
foreach(var question in questions)
{
writeNewQuestionToTblQuestions(question);
}
Try this
int Count = 0;
foreach (Control ctr in Panel1.Controls)
{
if (ctr is TextBox)
Count++;
}