elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Cómo Cambiar las Propiedades de un Control con "Reflection" ???
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Cómo Cambiar las Propiedades de un Control con "Reflection" ???  (Leído 2,240 veces)
LordBynary

Desconectado Desconectado

Mensajes: 12


Ver Perfil
Cómo Cambiar las Propiedades de un Control con "Reflection" ???
« en: 20 Enero 2015, 16:29 pm »

Hola a todos, he estado viendo el tema de "CodeDom" y "Reflection" en este link: http://www.codeproject.com/Articles/12852/Compile-and-Run-VB-NET-Code-using-the-CodeDom y tengo un pequeño problema con eso.

Bueno el tema es que quisiera saber: Cómo Puedo Cambiar las Propiedades de un Control con "Reflection" en Tiempo de Ejecución, les explico mejor mi duda y les planteo el escenario:

1.- Tengo un "Formulario" llamado "Form1".
2.- Tengo 2 "Textbox", llamados: "TextBox1" y "TextBox2" Respectivamente.
3.- También tengo un "Button" llamado "Button1".

Ahora lo que quiero hacer es lo siguiente:

- Que al ingresar en el "TextBox1" el texto "TextBox2.Enabled = False", y presionar el "Button1", se deshabilite automáticamente el TextBox2 en Tiempo de Ejecución.

Por Favor les pido que me ayuden, es urgente el tema.

Gracias a todos de antemano.



Elektro quisiera que me ayudes ahora sí aquí, o a los moderadores de este foro les pido que me ayuden con esto, o a cualquier persona que sepa algo sobre esto.



[MOD]: Está prohibido hacer doble post, utiliza el botón "Modificar" :P


« Última modificación: 20 Enero 2015, 19:05 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: Cómo Cambiar las Propiedades de un Control con "Reflection" ???
« Respuesta #1 en: 20 Enero 2015, 18:48 pm »

En el caso específico del problema que has expuesto, puedes hacerlo por ejemplo así:

Ten en cuenta que el siguiente código no está pulido, es solo un ejemplo, y se podría simplificar o parsear el string de otra manera más eficiente.

EDITO: Versión extendida:

Código
  1. Imports System.Reflection
  2. Imports System.Globalization
  3.  
  4. Public Class Form1
  5.  
  6.    Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
  7.    Handles Button1.Click
  8.  
  9.        Me.ParseControlInstruction("Textbox2.Enabled = False")
  10.        Me.ParseControlInstruction("Textbox2.Hide()")
  11.  
  12.    End Sub
  13.  
  14.    Private Sub ParseControlInstruction(ByVal instruction As String)
  15.  
  16.        Dim isProperty As Boolean
  17.        Dim isMethod As Boolean
  18.  
  19.        If instruction Like "*[.]*[!(]*[=]*" Then
  20.            isProperty = True
  21.  
  22.        ElseIf instruction Like "*[.]*[!=]*[(]*[)]" Then
  23.            isMethod = True
  24.  
  25.        Else
  26.            Throw New NotImplementedException(String.Format("Cannot recognize the instruction string: {0}", instruction))
  27.  
  28.        End If
  29.  
  30.        ' Fix whitespaces.
  31.        instruction = instruction.Trim({" "c})
  32.  
  33.        ' Fix Namespaces. (THIS IS NOT PROPERLY IMPLEMENTED)
  34.        If instruction.StartsWith("Me.", StringComparison.OrdinalIgnoreCase) Then
  35.            instruction = instruction.Remove(0, "Me.".Length)
  36.        End If
  37.  
  38.        Dim ctrlName As String = instruction.Substring(0, instruction.IndexOf("."c))
  39.  
  40.        If isProperty Then
  41.            Dim propName As String = instruction.Remove(0, ctrlName.Length + 1)
  42.            propName = propName.Substring(0, propName.IndexOf(" "c))
  43.  
  44.            Dim value As Object = instruction.Substring(instruction.IndexOf("="c) + 1).Trim({" "c})
  45.  
  46.            Me.SetControlProperty(ctrlName, propName, value, MyBase.Controls, searchChildrens:=True)
  47.  
  48.        ElseIf isMethod Then
  49.            Dim methodName As String = instruction.Remove(0, ctrlName.Length + 1).TrimEnd({"("c, ")"c})
  50.  
  51.            Dim methodParamsStr As String = instruction.Substring(instruction.IndexOf("("c) + 1)
  52.            methodParamsStr = methodParamsStr.Substring(0, methodParamsStr.LastIndexOf(")"c))
  53.            Dim methodParams As IEnumerable(Of Object) = methodParamsStr.Split({", "}, StringSplitOptions.RemoveEmptyEntries)
  54.  
  55.            Me.CallControlMethod(ctrlName, methodName, methodParams, MyBase.Controls, searchChildrens:=True)
  56.  
  57.        End If
  58.  
  59.    End Sub
  60.  
  61.    Private Sub SetControlProperty(ByVal ctrlName As String,
  62.                                   ByVal propName As String,
  63.                                   ByVal value As Object,
  64.                                   ByVal controlCollection As Control.ControlCollection,
  65.                                   Optional ByVal searchChildrens As Boolean = False,
  66.                                   Optional ByVal searchFlags As BindingFlags =
  67.                                                                 BindingFlags.IgnoreCase Or
  68.                                                                 BindingFlags.Instance Or
  69.                                                                 BindingFlags.Public Or
  70.                                                                 BindingFlags.NonPublic)
  71.  
  72.        Dim ctrl As Control = controlCollection.Find(ctrlName, searchChildrens).FirstOrDefault
  73.        Dim prop As PropertyInfo
  74.  
  75.        Select Case ctrl Is Nothing
  76.  
  77.            Case False
  78.                Try
  79.                    prop = ctrl.GetType().GetProperty(propName, searchFlags)
  80.  
  81.                Catch ex As AmbiguousMatchException
  82.                    Throw New AmbiguousMatchException(String.Format("More than one property found with the same name: {0}", propName))
  83.                    Exit Sub
  84.  
  85.                End Try
  86.  
  87.                Select Case prop Is Nothing
  88.  
  89.                    Case False
  90.                        Try
  91.                            prop.SetValue(ctrl, Convert.ChangeType(value, prop.PropertyType), Nothing)
  92.  
  93.                        Catch ex As Exception
  94.                            Throw
  95.  
  96.                        End Try
  97.  
  98.                    Case Else
  99.                        Throw New NullReferenceException(String.Format("Property not found by name: {0}", propName))
  100.  
  101.                End Select ' prop Is Nothing
  102.  
  103.            Case Else
  104.                Throw New NullReferenceException(String.Format("Control not found by name: {0}", ctrlName))
  105.  
  106.        End Select ' ctrl Is Nothing
  107.  
  108.    End Sub
  109.  
  110.    Private Sub CallControlMethod(ByVal ctrlName As String,
  111.                                  ByVal methodName As String,
  112.                                  ByVal methodParams As IEnumerable(Of Object),
  113.                                  ByVal controlCollection As Control.ControlCollection,
  114.                                  Optional ByVal searchChildrens As Boolean = False,
  115.                                  Optional ByVal searchFlags As BindingFlags =
  116.                                                                BindingFlags.IgnoreCase Or
  117.                                                                BindingFlags.Instance Or
  118.                                                                BindingFlags.Public Or
  119.                                                                BindingFlags.NonPublic)
  120.  
  121.        Dim ctrl As Control = controlCollection.Find(ctrlName, searchChildrens).FirstOrDefault
  122.        Dim method As MethodInfo
  123.  
  124.        Select Case ctrl Is Nothing
  125.  
  126.            Case False
  127.                Try
  128.                    method = ctrl.GetType().GetMethod(methodName, searchFlags)
  129.  
  130.                Catch ex As AmbiguousMatchException
  131.                    Throw New AmbiguousMatchException(String.Format("More than one method found with the same name: {0}", methodName))
  132.                    Exit Sub
  133.  
  134.                End Try
  135.  
  136.                Select Case method Is Nothing
  137.  
  138.                    Case False
  139.                        Try
  140.                            method.Invoke(ctrl, searchFlags, Nothing, methodParams.ToArray, CultureInfo.InvariantCulture)
  141.  
  142.                        Catch ex As Exception
  143.                            Throw
  144.  
  145.                        End Try
  146.  
  147.                    Case Else
  148.                        Throw New NullReferenceException(String.Format("Method not found by name: {0}", methodName))
  149.  
  150.                End Select ' prop Is Nothing
  151.  
  152.            Case Else
  153.                Throw New NullReferenceException(String.Format("Control not found by name: {0}", ctrlName))
  154.  
  155.        End Select ' ctrl Is Nothing
  156.  
  157.    End Sub
  158.  
  159. End Class

Saludos


« Última modificación: 20 Enero 2015, 20:45 pm por Eleкtro » En línea

LordBynary

Desconectado Desconectado

Mensajes: 12


Ver Perfil
Re: Cómo Cambiar las Propiedades de un Control con "Reflection" ???
« Respuesta #2 en: 20 Enero 2015, 23:33 pm »

Gracias "Elektro" pero me salen estos dos errores en tú código, mira: El primero es con la propiedad "FirstOrDefault"



Y luego este también: El segundo es con la propiedad "methodParams.ToArray"

« Última modificación: 20 Enero 2015, 23:35 pm por LordBynary » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: Cómo Cambiar las Propiedades de un Control con "Reflection" ???
« Respuesta #3 en: 21 Enero 2015, 06:39 am »

En las propiedades de tu proyecto, cambia el .Net Framework objetivo del proyecto a .Net framework 3.5 o superior, para añadir la referencia a LINQ.

Saludos
« Última modificación: 21 Enero 2015, 06:46 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines