I have a load of text boxes on an aspx page whose IDs are prefixed with 'txt' the rest of the ID has a corresponding property of the same name in a certain object. I want to be able to enumerate through these string properties and update them where a text box of the same name (with the prefix removed) is found. Any Ideas? I know by using a Dictionary I can get around the problem but it's not ideal.
You can do that using reflection:
MyObject data = new MyObject();
foreach (var pi in typeof(MyObject).GetProperties().Where(i =>
i.PropertyType.Equals(typeof(string)))
{
var control = FindControl("txt" + pi.Name) as ITextControl;
if (control != null)
pi.SetValue(data, control.Text, null);
}
You can work with the controls:
foreach (Control control in divXYZ.Controls)
if (control is TextBox)
((TextBox)control).Text = "whatever";
FindControl is another method you can use in your solution:
Control myControl = FindControl("txtYourID");
http://msdn.microsoft.com/en-us/library/486wc64h.aspx
just find all textbox controls on page and then fill coresponding properties using reflection.
Related
1I have problem that I am going to work with usercontrol in loop. In other word II want to change usercontrols property, but I cant. So I have usercontrol named ucProperty and in it many labels. I have called all of them differently such as LblNameModel, LblImageName, ... In my form there are many usercontrols - ucProperty1,2,.8 and now I want to change their properties (LblNameModel, LblImageName,..) dynamically and in loop.
I try this:
int i = 1;
foreach (Control contrl in this.Controls)
{
if (contrl.Name == ("ucProperty" + i.ToString()))
{
contrl.LblNameModel = "Model" + i.ToString();
contrl.LblImageName = "image" + i.ToString() + ".jpg";
i++;
}
}
enter image description here LblNameModel isnt accepted
But it doesnt work. My problem is properties as LblNameModel after contrl. isnt accepted to programm.
How I can change the properties in loop
and in my usercontrol ucProperty there is the code:
public string LblNameModel
{
get { return lblNameModel.Text; }
set { lblNameModel.Text = value; }
}
this is next result
You must filter and cast to your user controls
using System.Linq;
...
foreach (var uc in this.Controls.OfType<MyUserControlType>())
{
string number = uc.Name.SubString("ucProperty".Length);
uc.LblNameModel = "Model" + number;
uc.LblImageName = "image" + number + ".jpg";
}
If you simply loop through the controls, you get a loop variable typed as Control and you are not able to access properties specific to your user control. The OfType<T> extension method (namespace System.Linq) does both, filter and cast.
I assume that all of these user controls are named as ucProperty<number>. Otherwise add the check
if (uc.Name.StartsWith("ucProperty"))
Note that your approach with i has a problem if the user controls do not appear in the right order. I.e. If the foreach yields "ucProperty4" but i is 3 then this control will be skipped.
I need to align the text center for multiple richtextbox.
I found the solution to align the single richtextbox.
EX:
richtextbox1.SelectAll();
richtectbox1.SelectionAlignment = HorizantalAlignment.Center;
I dont want to enter this for every textboxes.
How to do this for multiple richtextbox using loop?
You can look for all the controls who are of type RichTextBox and do whatever you need to do like this:
foreach (var thisControl in this.Controls.OfType<RichTextBox>())
{
thisControl.SelectAll();
thisControl.SelectionAlignment = HorizontalAlignment.Center;
}
In addition to CodingYoshi's answer, if the Rich Text Boxes don't have a single common parent (i.e. the TextBoxes are dispersed on GroupBoxes, Tabs, etc), then you'll need to recurse from the topmost common parent (possibly the form itself) in order to find the RichTextBoxes, using a technique such as this one here:
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
You'll then be able to apply your alignment to all subordinate controls at any level from a given root coontrol (this is the root Form control in this example)
foreach (RichTextBox textBox in GetAll(this, typeof (RichTextBox)))
{
textBox.SelectAll();
textBox.SelectionAlignment = HorizontalAlignment.Center;
}
You need to create a list of RichTextBoxes, and then:
foreach(richtextbox in list)
{
t.SelectAll();
t.SelectionAlignment = HorizantalAlignment.Center;
}
You can also use [this] (How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?) post, to gather all your richtextboxes:
First you need to get all the child controls of the form into a list, and by changing the required property of each item in the list your objective can be met.
You can get all child controls by using a function like this:
public static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control
{
var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
return children.SelectMany(c => GetChildControls<TControl>(c)).Concat(children);
}
You can get all the RichText boxes like this
var richTextBoxes = this.GetChildControls<RichTextBox>();
foreach (RichTextBox rtb in richTextBoxes)
{
rtb.SelectionAlignment = HorizantalAlignment.Center;
}
Consider this as an idea, copy paste this code may have syntax errors.
I have a tab control that has listboxes on it some of which are created and named dynamically so I can't statically program their name. Is there a way to create an array of all the list box names on a give tabPage? I have been going nuts trying to figure out a way to do it.
it would look something like this (based on a winforms example)
List<string> listBoxNames = new List<string>();
foreach (Control control in tabPage1.Controls)
{
if (control.GetType() == typeof(ListBox))
{
listBoxNames.Add(control.Name);
}
}
Or the same thing in linq syntax
List<string> listBoxNames = (from Control control in tabPage1.Controls
where control.GetType() == typeof (ListBox)
select control.Name).ToList();
if you want to find all the listbox's in the tabpage again then see below
foreach (var listBoxName in listBoxNames)
{
ListBox listBox = (ListBox) tabPage1.Controls.Find(listBoxName, true)[0];
}
I have a List which has 16 Dictionary items, I want to assign the values of this 16 dictionaries into 16 different text fields. What I am doing now is this
txtAccountType.Text = SheetData[0]["KeyName"].ToString();
txtAccountName.Text = SheetData[1]["KeyName"].ToString();
txtAccountAddress.Text = SheetData[2]["KeyName"].ToString();
txtAccountActivationDate.Text = SheetData[3]["KeyName"].ToString();
txtAccountExpiry.Text = SheetData[4]["KeyName"].ToString();
SheetData is a instance of List class containing multiple dictionaries.
I thought of using the for loop as well but the problem is that it did not work because every time I used to see the last dictionaries value in all the text fields.
The above solution works fine for me but what if I get 15 dictionaries or 10 dictionaries in future, the solution I am using is not dynamic here so could you please suggest me on how can I improve this.
Its not possible to decide which data to assign for particular textbox. If any data can be assigned to any of the text box below code will work for you. It works like first element will be assigned to first textbox.
int i = 0;
foreach (Control ctl in controls)
{
if (ctl is TextBox)
{
TextBox txt = (TextBox)ctl;
txt.Text = SheetData[i]["KeyName"].ToString();
i++;
}
}
Here controls are the collection of ControlCollection object. For example you can collect it from form like this ControlCollection controls = this.form1.Controls;
I have a User Control, containing a Grid, containing a child control.
I want to get a reference to the child control from the code behind for the User Control.
This is what I have:
var childControl = (MyChildControlType)this.Grid.Children.Single(c => (string) c.GetValue(NameProperty) == "MyChildControlNameFromXAMLNameAttribute");
Ugly as a run over garbage can lid.
What is a neater way to do this?
You could either go with the name-hunting, along the lines of what's been suggested already:
var childControl = (MyChildControlType)this.Grid.FindName("MyChildControlNameEtc");
Or, if you wanted a more generic approach to what you're already trying (eg if you want to look up by a different property), you could try:
var childControl = (MyChildControlType)this.Grid.Children.OfType<FrameworkElement>().Single(f => f.Name == "Blah");
or
var childControl = (MyChildControlType)this.Grid.Children.OfType<MyChildControlType>().Single(f => f.Name == "Blah");
Or you could use the VisualTreeHelper, which would work with non-Grids, and would particularly work nicely if you needed to recurse down the visual tree:
for(int i = 0; i < VisualTreeHelper.GetChildrenCount(this.Grid); ++i)
{
var child = VisualTreeHelper.GetChild(this.Grid, i) as FrameworkElement;
if (child != null && child.Name == "Blah")
return child;
}
But really if you can just name it and access it from the codebehind normally like what John Bowen said that's by far the easiest.
Assigning a Name or x:Name to an element in XAML (unless it is inside a template) makes that element accessible from code-behind as a field with that name. So this is basically already declared and populated for you during InitializeComponent:
MyChildControlType MyChildControlNameFromXAMLNameAttribute;
and you can use it directly:
MyChildControlNameFromXAMLNameAttribute.Visibility = Visibility.Hidden;
May be this , Give x:Name to your childControl
var childControl = (MyChildControlType)MyGridNameFromXAMLNameAttribute.FindName("MyChildControlNameFromXAMLNameAttribute");