Mostrando entradas con la etiqueta General. Mostrar todas las entradas
Mostrando entradas con la etiqueta General. Mostrar todas las entradas

jueves, 5 de abril de 2012

Convertir Numero entre Decimal y Binario

Objectivo
Convertir numeros de Decimales a Binarios y de Binario a Decimal
 
Codigo C#
 
        private string ConvertDecimalToBinary(string decimaltoconvertto)
        {
            #region Determinar el binario
            int pruebaByte;

            StringBuilder sb = new StringBuilder();

            if (int.TryParse(decimaltoconvertto, out pruebaByte))
            {
                do
                {
                    if (pruebaByte % 2 == 0)
                    {
                        sb.Append("0");

                        pruebaByte = pruebaByte / 2;
                    }

                    else
                    {
                        sb.Append("1");

                        pruebaByte = pruebaByte / 2;
                    }

                } while (pruebaByte > 0);
            }

            else
            {
                return "Valor no valido! Favor introducir un valor entre 0-255";
            }
            #endregion Determinar el binario

            #region Manipular el binario
            // Convertir el valor en una matriz
            char[] binary = sb.ToString().ToArray();

            // invierto el orden de los elementos
            char[] reversed = binary.Reverse().ToArray();

            /*********************************************
            * Agregar codigo para manipular los bits     *
            *********************************************/

            // construir el binario ya ordenado
            StringBuilder sb2 = new StringBuilder();

            foreach (char item in reversed)
            {
                sb2.Append(item);
            }
            #endregion Manipular el binario

            #region Para representar el binario con 8 bits
            int by;

            int.TryParse(sb2.ToString(), out by);

            return by.ToString("00000000");
            #endregion Para representar el binario con 8 bits
        }

        private string ConvertBinaryToDecimal(string binarytoconvertto)
        {
            int mydecimal = 0;

            int f;

            for (int i = 0; i < binarytoconvertto.Length; i++)
            {
                if (new string(binarytoconvertto.ToCharArray().Reverse().ToArray()[i], 1) != "0")
                {
                    int.TryParse(new string(binarytoconvertto.ToCharArray().Reverse().ToArray()[i], 1), out f);

                    mydecimal += ((int)f) * ((int)Math.Pow(2, i));
                }

                else
                {
                    continue;
                }
            }

            return mydecimal.ToString();
        }
Codigo VB
Private Function ConvertDecimalToBinary(decimaltoconvertto As String) As String
 '#Region "Determinar el binario"
 Dim pruebaByte As Integer

 Dim sb As New StringBuilder()

 If Integer.TryParse(decimaltoconvertto, pruebaByte) Then
  Do
   If pruebaByte Mod 2 = 0 Then
    sb.Append("0")

    pruebaByte = pruebaByte / 2
   Else

    sb.Append("1")

    pruebaByte = pruebaByte / 2

   End If
  Loop While pruebaByte > 0
 Else

  Return "Valor no valido! Favor introducir un valor entre 0-255"
 End If
 '#End Region

 '#Region "Manipular el binario"
 ' Convertir el valor en una matriz
 Dim binary As Char() = sb.ToString().ToArray()

 ' invierto el orden de los elementos
 Dim reversed As Char() = binary.Reverse().ToArray()

 '********************************************
'            * Agregar codigo para manipular los bits     *
'            ********************************************


 ' construir el binario ya ordenado
 Dim sb2 As New StringBuilder()

 For Each item As Char In reversed
  sb2.Append(item)
 Next
 '#End Region

 '#Region "Para representar el binario con 8 bits"
 Dim by As Integer

 Integer.TryParse(sb2.ToString(), by)

 Return by.ToString("00000000")
 '#End Region
End Function

Private Function ConvertBinaryToDecimal(binarytoconvertto As String) As String
 Dim mydecimal As Integer = 0

 Dim f As Integer

 Dim i As Integer = 0
 While i < binarytoconvertto.Length
  If New String(binarytoconvertto.ToCharArray().Reverse().ToArray()(i), 1) <> "0" Then
   Integer.TryParse(New String(binarytoconvertto.ToCharArray().Reverse().ToArray()(i), 1), f)

   mydecimal += DirectCast(f, Integer) * DirectCast(Math.Pow(2, i), Integer)
  Else

   Continue While
  End If
  System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
 End While

 Return mydecimal.ToString()
End Function
Descripcion:
 
 
 

miércoles, 22 de febrero de 2012

Convertir numero en letra





Objetivo
Convertir números en su respectiva letras

Vista Previa
Blogger
 
Código C#
 
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ConvNumLetra
{
    public partial class NumeroEnLetraForm : Form
    {
        private static int comas;           // Cantidad de comas en el valor
        private static string[] digitos;    // Grupon de digito en el valor
        private static int td = 1;

        #region Enu_Digitos, Enumeracion con todos los digitos contenido en un numero
        enum Unidad { Cero = 0, Uno = 1, Dos = 2, Tres = 3, Cuatro = 4, Cinco = 5, Seis = 6, Siente = 7, Ocho = 8, Nueve = 9 };
        enum Decena { Once = 11, Dosce = 12, Trece = 13, Cotorce = 14, Quince = 15 };
        enum DecenaEntero { Diez = 10, Veinte = 20, Treinta = 30, Cuarenta = 40, Cincuenta = 50, Sesenta = 60, Setenta = 70, Ochenta = 80, Noventa = 90 };
        enum Centena { Cien = 100, Doscientos = 200, Trecientos = 300, Cuatrocientos = 400, Quinientos = 500, Seiscientos = 600, Seteciento = 700, Ochocientos = 800, novecientos = 900 };
        enum GroupSeparator { None = 0, Mil = 1, Millones = 2, Billones = 4, Trillones = 6, Cuatrillones = 8, Quintillones = 10, Sextillones = 12, Septillones = 14, Octillones = 16, Nonillones = 18 };

        #endregion Enu_Digitos, Enumeracion con todos los digitos contenido en un numero

        /// 
        /// Contructor
        /// 
        public NumeroEnLetraForm()
        {
            InitializeComponent();
            textBox1.Focus();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            richTextBox1.Text = ProccessStringMethod(textBox1.Text);
            comas = 0;
            digitos = null;
        }

        private string ProccessStringMethod(string value)
        {
            if (value.Contains(".") || (value.Contains(".") && value.Contains(",")))
            {
                //double dou = Convert.ToDouble(value);

                decimal de = Convert.ToDecimal(value);

                string worknumber = de.ToString("#,#.##", CultureInfo.CurrentCulture);

                string entero = worknumber.Substring(0, worknumber.IndexOf(CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator));

                string dec = worknumber.Substring(worknumber.IndexOf(CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator) + 1);

                Regex rex = new Regex("[0-9]");

                MatchCollection mc = rex.Matches(entero);

                StringBuilder sb2 = new StringBuilder();

                foreach (var item in mc)
                {
                    sb2.Append(item);
                }

                return DoConvertMethod(sb2.ToString()) + "con " + dec + "/100";
            }

            else
            {
                return DoConvertMethod(value) + "con 00/100";
            }
        }

        private string DoConvertMethod(string value)
        {
            Regex ex = new Regex(",");

            //double dou = Convert.ToDouble(value);

            decimal de = Convert.ToDecimal(value);

            /****************************************************************************
             * Realizar cualquiera operacion matematica o invocar un metodo que         *
             * la realice sobre el double, en este punto.                              *
             *                                                                          *
             ***************************************************************************/

            comas = ex.Matches(de.ToString("#,#.##", CultureInfo.CurrentCulture)).Count; // cantidad de comas

            char[] groupSeparator = new char[] { (CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator).ToCharArray()[0] }; // separador decimal de la referencia cultural actual

            digitos = de.ToString("#,#.##", CultureInfo.CurrentCulture).Split(groupSeparator);

            StringBuilder sb = new StringBuilder();

            foreach (string item in digitos)
            {
                try
                {
                    if (comas == 0) // No hay coma, entonce es un numero comun, ejemplo: 512
                    {
                        sb.Append(ProccessDigitMethod(item) + " ");
                        comas--;
                        break;
                    }

                    else
                    {
                        if (comas % 2 == 0)
                        {
                            // Cantidad de comas pares. Importante para la posicion en el diccionario.
                            comas = HelpDoConvertMethod(false, comas, sb, item);

                        }

                        else
                        {
                            // Cantidad de comas impares. Importante para la posicion en el diccionario.
                            comas = HelpDoConvertMethod(true, 01, sb, item);
                        }
                    }
                }
                catch (DivideByZeroException err)
                {
                    sb.Append(ProccessDigitMethod(item) + " " + (Enum.GetName(typeof(GroupSeparator), comas)) + " ");
                    comas--;
                }
            }
            return sb.ToString().ToLower();
        }

        private int HelpDoConvertMethod(bool mpm, int igs, StringBuilder sb, string item)
        {
            #region ItemLeght
            switch (item.Length)
            {
                #region Un Digito
                case 1:
                    if (item == "0")
                    {
                        sb.Append(ProccessDigitMethod(item));
                        comas--;
                    }
                    else
                    {
                        if ((item == "1") && comas >= 1) // singular en los millares que contienen la unidad 1
                        {
                            if (mpm == true)
                            {
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                                comas--;
                            }

                            else
                            {
                                string gs = (Enum.GetName(typeof(GroupSeparator), igs));
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + gs.Substring(0, gs.Length - 2) + " ");
                                comas--;
                            }
                        }
                        else
                        {
                            sb.Append(ProccessDigitMethod(item) + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                            comas--;
                        }
                    }
                    break;
                #endregion Un Digito

                #region Dos Digitos
                case 2:
                    if (item == "00")
                    {
                        sb.Append(ProccessDigitMethod(item));
                        comas--;
                    }
                    else
                    {
                        if ((item == "01") && comas > 1) // singular en los millares que contienen la unidad 1
                        {
                            if (mpm == true)
                            {
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                                comas--;
                            }

                            else
                            {
                                string gs = (Enum.GetName(typeof(GroupSeparator), igs));
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + gs.Substring(0, gs.Length - 2) + " ");
                                comas--;
                            }
                        }
                        else
                        {
                            sb.Append(ProccessDigitMethod(item) + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                            comas--;
                        }
                    }
                    break;
                #endregion Dos Digitos

                #region Tres Digitos
                case 3:
                    if (item == "000")
                    {
                        //int x = comas;
                        if (digitos[comas - 1] != "000") // item anterior al actual en la matriz.
                        {                            
                            if (comas % 2 == 0)
                            {
                                sb.Append(ProccessDigitMethod(item) + (Enum.GetName(typeof(GroupSeparator), comas)) + " ");
                                comas--;
                            }

                            else
                            {
                                sb.Append(ProccessDigitMethod(item) + " ");
                                comas--;
                            }
                        }

                        else
                        {
                            sb.Append(ProccessDigitMethod(item));
                            //comas--;

                            if (td>0 && td <= 3)
                            {
                                sb.Append((Enum.GetName(typeof(GroupSeparator), comas)) + " ");
                                //comas--;
                                td += td;
                            }
                            comas--;
                        }
                    }
                    else
                    {
                        if ((item == "001" || item.Substring(1, 2) == "01") && comas > 1)
                        {
                            if (mpm == true)
                            {
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                                comas--;
                            }

                            else
                            {
                                string gs = (Enum.GetName(typeof(GroupSeparator), igs));
                                string rs = ProccessDigitMethod(item).ToLower().Replace("uno", "un");
                                sb.Append(rs + " " + gs.Substring(0, gs.Length - 2) + " ");
                                comas--;
                            }
                        }
                        else
                        {
                            sb.Append(ProccessDigitMethod(item) + " " + (Enum.GetName(typeof(GroupSeparator), igs)) + " ");
                            comas--;
                        }
                    }
                    break;
                    #endregion Tres Digitos
            }
            #endregion ItemLeght
            return comas;
        }

        private string ProccessDigitMethod(string value)
        {
            string re = string.Empty;

            #region ValueLeght
            switch (value.Length)
            {
                #region Un Digito
                case 1:
                    if (value == "0")
                    {
                        re = string.Empty;
                    }
                    else
                    {
                        re = (Enum.GetName(typeof(Unidad), Convert.ToInt32(value)));
                    }
                    break;
                #endregion Un Digito

                #region Dos Digitos
                case 2:
                    if (value == "00")
                    {
                        re = string.Empty;
                    }

                    else
                    {
                        re = ProccessTwoDigitMethod(value);
                    }
                    break;
                #endregion Dos Digitos

                #region Tres Digitos
                case 3:
                    Regex rex2 = new Regex("0");

                    if (value.Contains("0")) // contiene cero
                    {
                        switch (rex2.Matches(value).Count) // cantidad de ceros
                        {
                            #region un cero
                            case 1: // un cero
                                Regex rex3 = new Regex(@"0"); // localizamo el cero

                                switch (value.IndexOf(rex3.Match(value).ToString())) // Posicion del cero
                                {
                                    case 0: // A la izquierda, ej: 011
                                        re = ProccessTwoDigitMethod(value.Substring(1, 2));
                                        break;

                                    case 1: // Centro, ej: 101
                                        if (Convert.ToInt32(value.Substring(0, 1)) == 5) // lleva el prefijo ciento
                                        {
                                            re = (Enum.GetName(typeof(Centena), (Convert.ToInt32(value.Substring(0, 1) + "00")))) + " " + Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(2, 1))).ToLower();
                                        }

                                        else
                                        {
                                            if (Convert.ToInt32(value.Substring(0, 1)) == 1)
                                            {
                                                re = "Ciento " + (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(2, 1))).ToLower());
                                            }
                                            else
                                            {
                                                re = (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(0, 1)))) + "Ciento " + (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(2, 1))));
                                            }
                                        }
                                        break;

                                    case 2: // A la derecha, ej: 110
                                        if (Convert.ToInt32(value.Substring(0, 1)) == 5) // lleva el prefijo ciento
                                        {
                                            re = (Enum.GetName(typeof(Centena), (Convert.ToInt32(value.Substring(0, 1) + "00")))) + " " + ProccessTwoDigitMethod(value.Substring(1, 2)).ToLower();
                                        }

                                        else
                                        {
                                            if (Convert.ToInt32(value.Substring(0, 1)) == 1)
                                            {
                                                re = "Ciento " + ProccessTwoDigitMethod(value.Substring(1, 2)).ToLower();
                                            }
                                            else
                                            {
                                                re = (Enum.GetName(typeof(Centena), Convert.ToInt32(value.Substring(0, 1) + "00"))) + " " + ProccessTwoDigitMethod(value.Substring(1, 2)).ToLower(); ;
                                            }
                                        }
                                        break;
                                }
                                break;
                            #endregion un cero

                            #region Dos ceros
                            case 2: // Dos ceros
                                Regex rex = new Regex(@"[1-9]"); // localizamos numero diferente de cero

                                switch (value.IndexOf(rex.Match(value).ToString())) // Posicion del numero
                                {
                                    case 0: // A la izquierda, ej: 100
                                        re = (Enum.GetName(typeof(Centena), Convert.ToInt32(value)));
                                        break;

                                    case 1: // Centro, ej: 010
                                        re = (Enum.GetName(typeof(DecenaEntero), Convert.ToInt32(value.Substring(1, 2))));
                                        break;

                                    case 2: // A la derecha, ej: 001
                                        re = (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(2, 1))));
                                        break;
                                }
                                break;
                            #endregion Dos ceros

                            #region Tres ceros
                            case 3: // Tres ceros
                                re = string.Empty;
                                break;
                                #endregion Tres ceros
                        }
                    }

                    else // no contiene cero
                    {
                        if ((value.Substring(0, 1)) == "1")  // sufijo ciento
                        {
                            re = "Ciento " + ProccessTwoDigitMethod(value.Substring(1, 2)).ToLower();
                        }

                        else
                        {
                            re = (Enum.GetName(typeof(Centena), (Convert.ToInt32(value.Substring(0, 1) + "00")))) + " " + ProccessTwoDigitMethod(value.Substring(1, 2));
                        }
                    }
                    break;
                #endregion Tres Digitos

                #region Cero Digitos
                default:
                    re = "Instroduzca un numero";
                    break;
                    #endregion Cero Digitos
            }
            #endregion ValueLeght

            return re;
        }

        private static string ProccessTwoDigitMethod(string value)
        {
            if (value.Contains("0")) // Contiene cero
            {
                if (value == "00") // dos cero, eje: 00
                {
                    return string.Empty;
                }

                else
                {
                    if (value.IndexOf("0") == 0) // cero a la izquierda, eje: 01
                    {
                        return (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(1, 1))));
                    }

                    else // cero a la derecha, eje: 10
                    {
                        return (Enum.GetName(typeof(DecenaEntero), Convert.ToInt32(value)));
                    }
                }
            }

            else // No contiene cero
            {
                if (Convert.ToInt32(value) > 10 && Convert.ToInt32(value) < 16) // busco en el grupo de decena 
                {
                    return Enum.GetName(typeof(Decena), Convert.ToInt32(value));
                }

                else
                {
                    if (Convert.ToInt32(value) > 15 && Convert.ToInt32(value) < 20)
                    {
                        return "Dieci" + (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(1, 1)))).ToLower();
                    }

                    else
                    {
                        if ((value.Substring(0, 1)) == "2")
                        {
                            return "Veinti" + (Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(1, 1)))).ToLower();
                        }

                        else
                        {
                            return (Enum.GetName(typeof(DecenaEntero), Convert.ToInt32(value.Substring(0, 1) + 0))) + " y " + Enum.GetName(typeof(Unidad), Convert.ToInt32(value.Substring(1, 1))).ToLower();
                        }
                    }
                }
            }
        }
    }
}
Descarga
Csahrp (C#) Visual basic (VB)
Descripción:

lunes, 22 de agosto de 2011

Metodo Generico

Objectivo
Crear un metodo que no este sujeto a un query especifico y que retorne un control poblado de datos.
Requisito:
  • Visual Estudio 2008 o Superior
  • Agregar una conexion a la base de datos con la que quiere interactual, para este ejemplo se utilizo la base de datos AdventureWorks descargada del site codeplex
  • Agregar un label al formulario para reflejar el valor selecciona del control
Nota:
  • Para realizar esta practica agregue u projecto tipo web y pegue este codigo en el codebehind de la pagina Default.aspx
  • Este codigo trabaja bien con controles de lista de aplicaciones web y aplicaciones winform, tales como:
  1. CheckBoxList
  2. DropDownList
  3. ListBox y
  4. RadioButtonList


Codigo C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Globalization;
using System.ComponentModel;

public partial class _Default : System.Web.UI.Page
{
    #region Evento Load de la pagina
    protected void Page_Load(object sender, EventArgs e)
    {
        AdventureWorks_DataModel.AdventureWorks_DataEntities db = new AdventureWorks_DataModel.AdventureWorks_DataEntities();

        form1.Controls.Add(ControlBuilder<AdventureWorks_DataModel.Product, DropDownList>(db.Products.Select(dd => dd).ToList(), "ProductID", "Name", "dd1", "hola"));
    }
    #endregion Evento Load de la pagina

    #region Generic Method
    private static U ControlBuilder<T, U>(List<T> row, string datavaluefieldname, string datatextfieldname, string id, string Etiqueta)
        where T : class
        where U : class
    {
        Type ControlToReturnType = typeof(U);

        DropDownList ControlToReturn = (DropDownList)ControlToReturnType.InvokeMember
            (
            null,
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.CreateInstance,
            null,
            null,
            null
            );
        
        ControlToReturn.ID = id;
        ControlToReturn.AutoPostBack = true;
        ControlToReturn.CausesValidation = false;
        ControlToReturn.Width = System.Web.UI.WebControls.Unit.Percentage(100);
        ControlToReturn.SelectedIndexChanged += new EventHandler(ControlToReturn_SelectedIndexChanged);

        foreach (T item in row)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(item);

            System.ComponentModel.PropertyDescriptor MyProperty1 = properties.Find(datatextfieldname, false);
            System.ComponentModel.PropertyDescriptor MyProperty2 = properties.Find(datavaluefieldname, false);

            ListItem li = new ListItem();

            li.Text = MyProperty1.GetValue(item).ToString();
            li.Value = MyProperty2.GetValue(item).ToString();
            ControlToReturn.Items.Add(li);
        }

        ListItem EtiquetaApertura = new ListItem();
        EtiquetaApertura.Enabled = true;
        EtiquetaApertura.Selected = true;
        EtiquetaApertura.Value = null;
        EtiquetaApertura.Text = Etiqueta;
        ControlToReturn.Items.Insert(0, EtiquetaApertura);

        return ControlToReturn as U;
    }
    #endregion GenericMethod

    #region Manejador de evento para el control
    static void ControlToReturn_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dl = (DropDownList)sender;
        Page page = (Page)dl.NamingContainer;

        Label lb = (Label)page.FindControl("lb1");

        lb.Text = dl.SelectedValue;

    }
    #endregion Manejador de evento para el control
}
            
Descripcion:
  1. En el evento load de la pagina agregamos el contexto de la base de datos que utilizaremos para realizar el query de los campos que queremos que se vizualicen en el control
    protected void Page_Load(object sender, EventArgs e)
        {
            AdventureWorks_DataModel.AdventureWorks_DataEntities db = new AdventureWorks_DataModel.AdventureWorks_DataEntities();
        }
  2. Agregamos el control a la coleccion de controles del formulario de la pagina invocando el metodo y pasandoles los argumentos requerido. Al metodo les estamo diciendo:
    • Que como parametro de entrada utilizaremos el tipo Product.
    • Que como parametro de salida nos retorne un DropDownList para visualizacion los datos.
    Y como argumento les estamos pasando:
    • Query que retorna una lista con todas las filas de la base de datos.
    • "ProductID", como el valor del control ListItems.
    • "Name", como el valor a mostrar en el control ListItems.
    • "dd1", como el ID del control.
    • "Seleccione una Opcion", como Etiqueta del control.
    protected void Page_Load(object sender, EventArgs e)
        {
            form1.Controls.Add(ControlBuilder<AdventureWorks_DataModel.Product, DropDownList>(db.Products.Select(dd => dd).ToList(), "ProductID", "Name", "dd1", "Seleccione una Opcion"));
        }
  3. Procedemos a la declaracion del metodo que contiene la siguiente firma
    • Un parametro Generico de entrada de Tipo T.
    • Un parametro Generico de salida de Tipo U.
    Y como Parametros Formales:
    • Una lista de tipo T.
    • Un valor para el control ListItems.
    • Un valor para mostrar en el control ListItems.
    • El ID del control.
    • Una etiqueta de apertura.
    • Y por ultimo restringimos el argumento de tipo a tipo de referencia
    private static U ControlBuilder<T, U>(List<T> row, string datavaluefieldname, string datatextfieldname, string id, string Encabezado)
            where T : class
            where U : class
        {
        }
                        
  4. Pasamos a la implementacion del metodo en donde obtenemos el tipo de valor pasado para la creacion de nuestra instancia
  5. Type ControlToReturnType = typeof(U);
  6. Creamos una instancia del tipo suministrado, para crear la instancia invocamos el metodo InvokeMember() del tipo.
  7. DropDownList ControlToReturn = (DropDownList)ControlToReturnType.InvokeMember
                (
                null,
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.CreateInstance,
                null,
                null,
                null
                );
  8. Seteamos las propiedades e instanciamos nuestro manejador de evento
  9. ControlToReturn.ID = id;
    ControlToReturn.AutoPostBack = true;
    ControlToReturn.CausesValidation = false;
    ControlToReturn.Width = System.Web.UI.WebControls.Unit.Percentage(100);
    ControlToReturn.SelectedIndexChanged += new EventHandler(ControlToReturn_SelectedIndexChanged);
    
  10. Procesamos las filas pasada al metodo mediante el parametro formal "List<T> Rows" para poder almar nuestro control ListItems
  11. foreach (T item in row)
            {
                // Creo una nueva colleccion y le asigno a esta las prepiedades de item.
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(item);
    
                // Seteo el PropertyDescriptor a la propiedad especificada.
                System.ComponentModel.PropertyDescriptor MyProperty1 = properties.Find(datatextfieldname, false);
                System.ComponentModel.PropertyDescriptor MyProperty2 = properties.Find(datavaluefieldname, false);
    
                ListItem li = new ListItem();
    
                li.Text = MyProperty1.GetValue(item).ToString();
                li.Value = MyProperty2.GetValue(item).ToString();
                ControlToReturn.Items.Add(li);
            }
    
            ListItem EtiquetaApertura = new ListItem();
            EtiquetaApertura.Enabled = true;
            EtiquetaApertura.Selected = true;
            EtiquetaApertura.Value = null;
            EtiquetaApertura.Text = Encabezado;
            ControlToReturn.Items.Insert(0, EtiquetaApertura);
    
            return ControlToReturn as U;
        }
    • Descompongo la fila en cada uno de sus columnas o campos mediante TypeDescriptor.GetProperties (Método) y se los agregos a mi coleccion
      PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(item);;;;
      
    • Localizo los campos DataTextField y DataValueField dentro de la coleccion para asignarselo a la propiedad Text y Value respectivamente del control ListItem
    • System.ComponentModel.PropertyDescriptor MyProperty1 = properties.Find(datatextfieldname, falseSystem.ComponentModel.PropertyDescriptor MyProperty2 = properties.Find(datavaluefieldname, false);
      
    •  Creo mi instancia del control ListItem, pasandole el valor de los campos: DataTextField y DataValueField mediante PropertyDescriptor.GetValue (Método), a sus propiedades: Text y Value respectivamente y lo agrego a la coleccion de controles ListItem del control a retornar en el parametro generico del metodo
    • ListItem li = new ListItem();m();
      
      li.Text = MyProperty1.GetValue(item).ToString();
      li.Value = MyProperty2.GetValue(item).ToString();
      
      ControlToReturn.Items.Add(li);
    • Creamos una instancia del control ListItem que servira como etiqueta de apertura del control a retornar seteando sus propiedades y agregando a la posicion cero dentro de la coleccion de controles ListItem del control a retornar en el parametro generico del metodo
    • ListItem EtiquetaApertura = new ListItem();
      EtiquetaApertura.Enabled = true;
      EtiquetaApertura.Selected = true;
      EtiquetaApertura.Value = null;
      EtiquetaApertura.Text = Encabezado;
      ControlToReturn.Items.Insert(0, EtiquetaApertura);
  12. Retornamos el control
  13. return ControlToReturn as U;
  14. Por ultimo implementamos el metodo manejador para el evento OnSelectedIndexChanged del control retornado
  15. static void ControlToReturn_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList dl = (DropDownList)sender;
            Page page = (Page)dl.NamingContainer;
    
            Label lb = (Label)page.FindControl("lb1");
    
            lb.Text = dl.SelectedValue;
    
        }