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.
Asked
Active
Viewed 66 times
2
-
This seems like a difficult design to deal with. Is it at all subject to change? Whenever you've designed something for which the only solution seems to be "use reflection" you have to ask yourself if you're sure you couldn't design it better. – Servy Aug 23 '12 at 16:03
-
If you feel an answer helps you then you should upvote it and/or mark it as the answer by clicking the checkbox next to it, don't just edit it into your question. – Servy Aug 23 '12 at 16:06
-
I had to wait to click the checkbox it was locked out. Thanks everyone. – Roooss Aug 23 '12 at 16:22
3 Answers
4
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);
}

Amiram Korach
- 13,056
- 3
- 28
- 30
-
So looking at what you have there this will get every property form my object and update it with the value of the matching text box? – Roooss Aug 23 '12 at 16:00
-
The only thing being i only want to get string properties not all of them – Roooss Aug 23 '12 at 16:01
-
1
1
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");

rGiosa
- 355
- 1
- 4
- 16
0
just find all textbox controls on page and then fill coresponding properties using reflection.

Piotr Perak
- 10,718
- 9
- 49
- 86