How to get instance of control by name

  • Thread starter Thread starter Jaroslav Jakes
  • Start date Start date
J

Jaroslav Jakes

Hi,

imagine having an INI-file with entries like:

# key=Control / value=Text property of control
controlA=bla bla bla
controlB=bla bla bla

controlA and controlB are different controls of types like TextBox, etc.

Closing form will write INI-file, storing control names and text property of
these
Loading form will read INI-file and set text value of corresponding control

quite a simple task, if you'll do it as follows:

.....

switch (iniControl)
{
case "controlA" :
controlA.Text = iniValue;
break;
....
}

....

But what about a more generic solution?

Assuming that the key-value of INI-file is a known control, an instance
within the form, what about a solution like:

- get instance of the control by its name
- set value from INI-file to Text-property

Tried to solve this by using reflection - something like
GetType(iniControl), but never suceeded.

What do you think how this could be solved?

Thanks and regards - Jari
 
Hi,

The way I'd do it is ..

First either read your ini file into a hashtable or place all of your
controls into a hashtable, so that you have the Name as the key to the
object.

Then read down the other one and get the key / object from the hashtable and
set the value.

Like below, and yes I know this is only seudo code.

LoadEvent Sub
For each textValue in .ini file
Hashtable.Add(textValue, ControlName)
End for

For each ctrl as Control in Me.Controls
If HashTable.Contains(ctrl.Name) Then
ctrl.Text = Cstr(Hashtable(ctrl.Name))
End if
End For

End Sub

I'm sure there are loads of other ways to do this, and no doubt, you'll get
a few more replies with differing methods by the end of the day.

but either way, HTH.
Rigga.
 
Hi folks,

Javier, there is no FindByName method in the control collection.
Actually Name property is not guarantied to be set. If you create a control
dynamically in the code it might have no name set.

IMHO Rigga's suggestion could be a way to go
 
Stoitcho Goutsev (100) said:
Javier, there is no FindByName method in the control collection.
Actually Name property is not guarantied to be set. If you create a control
dynamically in the code it might have no name set.

IMHO Rigga's suggestion could be a way to go

Ooops, that's right, I was messing Delphi here, my bad!

Sorry about the confusion

Javier Campos
 
Back
Top