Reputation: 477
Hi i want to make this code shorter:
tb1n.Text = Settings2.Default.tb1n;
tb2n.Text = Settings2.Default.tb2n;
tb3n.Text = Settings2.Default.tb3n;
tb4n.Text = Settings2.Default.tb4n;
tb5n.Text = Settings2.Default.tb5n;
tb6n.Text = Settings2.Default.tb6n;
tb7n.Text = Settings2.Default.tb7n;
tb8n.Text = Settings2.Default.tb8n;
tb9n.Text = Settings2.Default.tb9n;
tb10n.Text = Settings2.Default.tb10n;
tb11n.Text = Settings2.Default.tb11n;
tb12n.Text = Settings2.Default.tb12n;
tb13n.Text = Settings2.Default.tb13n;
Later I will add more settings to load and I need make it shorter but I don´t know how.
I tried to get this code to string like this:
int i = 1;
do
{
string tbload = "tb" + i + "n.Text = Settings2.Default.tb" + i + "n";
i++;
} while (i == 13);
But then I realize this is not good solution because execute code from string is hard to do and I don´t like it.
Upvotes: 0
Views: 148
Reputation: 3014
You can store your TextBoxes and your strings in a list like this:
List<TextBox> TextBoxes = new List<TextBox>() {
tb1n,
tb2n,
tb3n,
...
};
List<string> mySettings = new List<string>(){
Settings2.Default.tb1n,
Settings2.Default.tb2n,
Settings2.Default.tb3n,
...
};
foreach (TextBox item in TextBoxes)
{
item.Text = mySettings[TextBoxes.FindIndex(a => a.Name == item.Name)];
}
And then you can use a foreach loop to give every TextBox it's Text property value.
Upvotes: 1
Reputation: 921
You can create visual tree helper class and find all textbox instances on view.
Helper class:
public static class TreeHelper
{
public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
{
if (depObj == null) yield break;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var children = child as T;
if (children != null)
yield return children;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
}
Call
var children = this.FindVisualChildren<TextBox>();
foreach (var child in children)
{
child.Text = Settings.Default[child.Name].ToString();
}
Upvotes: 2