views:

72

answers:

5

hello

I'm working with .NETCF framwork in c#, and I want to know if I can access the controls somehow like this:

string field="txtName";
this.Controls[field];

or is this impossibile?

A: 

I don't see why it would be wrong, the indexer expects a string, and you're passing a string, so for me it's correct.

Shimrod
a control collection takes an int, you'd need FindControl
seraphym
this.Controls expects integer indexes. I want to know if I can acces the controls by name.
arnoldino
Yes you are right, I was too quick... As other said, you'll need to use `FindControl` method. (I should have written "If the indexer expects..." :-)
Shimrod
+2  A: 

I think the method you're after is FindControl - you'll find that method on anything with a Controls collection.

Jamiec
this would be perfect, but in Compact framework I don't have this method
arnoldino
A: 

It is possible to reference a control in the control collection by name (stirng) or index (int). The only thing you will need to do additionally is cast the control into the type of object it is. Something like the following.

MyControl c (MyControl)this.Controls["ControlName"];

Enjoy!

Doug
this isn't good either because the indexer expects integer values
arnoldino
A: 

As I can see, on Compact Framework there is no such method.

Please enlighten me if I'm wrong.

arnoldino
A: 

What about using Linq?

var myControl = this.Controls.Cast<Control>().OfType<WhateverControlType>().FirstOrDefault(cont => cont.ID == "myControlId");

Something like that?

mgroves
I used this:var myControl = this.Controls.Cast<Control>().OfType<TransparentLabel>().FirstOrDefault(cont => cont.Name = myStr);the result:Error 4 Cannot convert lambda expression to delegate type 'System.Func<SmartDeviceProject1.TransparentLabel,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type D:\JOB\VS C#\CONTIPLAY\V2\SmartDeviceProject1\Forms\frmMachines.cs 185 109 SmartDeviceProject1
arnoldino
well I didn't try it in VS, but I think something -like- that should work.
mgroves
I see: you should use '==' not '='
mgroves
If that works, you can make it an extension method 'FindControl' on ControlCollection
mgroves
cool stuff. thank you very much
arnoldino