Adding different controls having same names in C# Windows Form?

The Controlsstring indexer returns the first control whose name matches the string. It will be hit and miss with your code but you probably have a ComboBox already added to the form with that same name. The next statements go kaboom because you cannot cast a ComboBox to a TextBox.

The Controlsstring indexer returns the first control whose name matches the string. It will be hit and miss with your code but you probably have a ComboBox already added to the form with that same name. The next statements go kaboom because you cannot cast a ComboBox to a TextBox.

Of course, do try to do the sane thing, give these controls different names.

I want to know that these all are added to form with same name. How? – Javed Akram Nov 28 '10 at 18:43 Erm, just iterate Controls and count the ones with that name?

What is the point of this? – Hans Passant Nov 28 '10 at 18:45.

This. Controls"myControl" returns the first control named myControl. This is a TextBox, not a Label.

Instead of accessing them through the Controls collection, you should store your controls in fields in the form class (perhaps using Lists).

Here is one idea that might help you: void SetControlText(Type controlType, string controlName, string text) { foreach (var ctl in this.Controls.OfType()) { if (ctl.GetType() == controlType && ctl. Name == controlName) { ctl. Text = text; break; } } } Or with LINQ only: var item = this.Controls.OfType().

Where(j => j.GetType() == controlType && j. Name == controlName).FirstOrDefault(); if (item! = null) item.

Text = text; Simply call the above function like so: SetControlText(typeof(Button), "myButton", "Text was set! "); This function will iterate through all of the controls on the form, and when it finds the control type you specify with the name you specify, it will update the controls . Text field.

Thanks, Matthew.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions