tag:blogger.com,1999:blog-55046611779839962342023-11-15T08:20:51.025-05:00Angel Rafael Jimenez GuillermoAngel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.comBlogger6125tag:blogger.com,1999:blog-5504661177983996234.post-20926685047150779172015-07-15T00:03:00.000-05:002015-07-21T15:24:13.123-05:00Impuesto Sobre la renta<h2 style="text-align: center">Tassa de interes anual hasta el 2016 aplicado a la escala salarial en Republica Dominicana</h2>
<h3>
<strong>Objetivo</strong></h3>
<p>
Calcular la tasa de interes anual aplicado a la escala salarial de la Republica dominicana hasta el 2016:<br />
1. Renta hasta RD$ 399,923.00 = Exento
<br />
2. Renta desde RD$ 399,923.01 hasta RD$ 599,884.00 = 15% del excedente de RD$ 399,923.01
<br />
3. Renta desde RD$ 599,884.01 hasta RD$ 833,171.00 = RD$29,994.00 mas el 20% del excedente de RD$ 599,884.01
<br />
4. Rentas desde RD$ 833,171.01 en adelante = RD$ 76,652.00 más el 25% del excedente de RD$ 833,171.01
</p>
<h3>Nota</h3>
<p>Esta es una aplicacion de escritorio, pero puede ser facirmente aplicado a una aplicacion web</p>
<h3>Vista previa</h3>
<p>
<img alt="Vista Previa" src="http://1drv.ms/1MbxWCn" />
</p>
<h3>
<strong>Codigo C#</strong></h3>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">
private void button1_Click(object sender, EventArgs e)
{
double SueldoBruto = 0; // Sueldo bruto ingresado por el usuario.
double ISR = 0; // Impuesto Sobre la Renta.
const double AFP = 2.87; // Administradoras de fondos de pensiones.
const double ARL = 3.04; // Administradora de riesgos laborales.
const double LISR2 = 399923.01 / 12; // Limite inferior de la escala 2.
const double LISR3 = 599884.01 / 12; // Limite inferior de la escala 3.
const double LISR4 = 833171.01 / 12; // Limite inferior de la escala 4.
const double PCISR2 = 15.0 / 12; // Porciento aplicado a la escala 2.
const double PCISR3 = 20.0 / 12; // Porciento aplicado a la escala 3.
const double PCISR4 = 25.0 / 12; // Porciento aplicado a la escala 4.
const double incr3 = 29994.0 / 12; // Valor fijo aplicado a la escala 3.
const double incr4 = 76652.0 / 12; // Valor fijo aplicado a la escala 4.
if ((double.TryParse(textBox1.Text, out SueldoBruto)))
{
// determinar el valor de ISR segun la escala salarial
//No hay decuento, segun la escala 1
if ((SueldoBruto <= LISR2))
{
ISR += ISR;
} // 15% anual, segun la escala 2
else
{
double excedente;
if ((SueldoBruto <= LISR3))
{
// como es al excedente de LISR2, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR2);
// determino el descuento segun escala 2
ISR = (excedente * PCISR2) / 100;
} // 20% anual, , segun la escala 3
else
{
if ((SueldoBruto <= LISR4))
{
// como es al excedente de LISR3, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR3);
// determino el descuento mas incr3, segun la escala 3
ISR = ((excedente * PCISR3 / 100) + (incr3));
} // 25% anual, , segun la escala 4
else
{
// como es al excedente de LISR4, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR4);
// determino el descuento mas incr4, segun la escala 4
ISR = ((excedente * PCISR4 / 100) + (incr4));
}
}
}
double SueldoNexto = SueldoBruto - (((SueldoBruto * AFP) / 100) + ((SueldoBruto * ARL) / 100) + (ISR));
listBox1.Items.Clear();
listBox1.Items.Add("Sueldo Bruto: \tRD$" + Convert.ToString(SueldoBruto));
listBox1.Items.Add("AFP: \t\t" + Convert.ToString(AFP) + "%");
listBox1.Items.Add("ARL: \t\t" + Convert.ToString(ARL) + "%");
listBox1.Items.Add("ISR: \t\t" + Convert.ToString(ISR) + "%");
listBox1.Items.Add("Total a descontar: \tRD$" + Convert.ToString(((SueldoBruto * AFP) / 100) + ((SueldoBruto * ARL) / 100) + (ISR)));
listBox1.Items.Add("Sueldo Neto: \tRD$" + Convert.ToString(SueldoNexto));
}
else
{
MessageBox.Show("Ingrese sueldo");
}
}
</pre>
<h3><strong>Codigo Visual basic</strong></h3>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SueldoBruto As Double REM Sueldo bruto ingresado por el usuario.
Dim ISR As Double = 0 REM Impuesto Sobre la Renta.
Const AFP As Double = 2.87 REM Administradoras de fondos de pensiones.
Const ARL As Double = 3.04 REM Administradora de riesgos laborales.
Const LISR2 As Double = 399923.01 / 12 REM Limite inferior de la escala 2
Const LISR3 As Double = 599884.01 / 12 REM Limite inferior de la escala 3
Const LISR4 As Double = 833171.01 / 12 REM Limite inferior de la escala 4
Const PCISR2 As Double = 15 / 12 REM Porciento aplicado a la escala 2
Const PCISR3 As Double = 20 / 12 REM Porciento aplicado a la escala 3
Const PCISR4 As Double = 25 / 12 REM Porciento aplicado a la escala 4
Const incr3 As Double = 29994.0 / 12 REM Valor fijo aplicado a la escala 3
Const incr4 As Double = 76652.0 / 12 REM Valor fijo aplicado a la escala 4
If (Double.TryParse(TextBox1.Text, SueldoBruto)) Then
REM determinar el valor de ISR segun la escala salarial
If (SueldoBruto <= LISR2) Then 'No hay decuento, segun la escala 1
ISR = ISR
Else REM 15% anual, segun la escala 2
Dim excedente As Double
If (SueldoBruto <= LISR3) Then
REM como es al excedente de LISR1, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR2)
REM determino el descuento segun escala 2
ISR = (excedente * PCISR2) / 100
Else REM 20% anual
If (SueldoBruto <= LISR4) Then
REM como es al excedente de LISR2, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR3)
REM determino el descuento mas incr1, segun la escala 3
ISR = ((excedente * PCISR3 / 100) + (incr3))
Else REM 25% anual
REM como es al excedente de LISR3, debemos hacer una resta con el sueldo
excedente = SueldoBruto - (LISR4)
REM determino el descuento mas incr2, segun la escala 4
ISR = ((excedente * PCISR4 / 100) + (incr4))
End If
End If
End If
Dim SueldoNexto As Double = SueldoBruto - (((SueldoBruto * AFP) / 100) + ((SueldoBruto * ARL) / 100) + (ISR))
ListBox1.Items.Clear()
ListBox1.Items.Add("Sueldo Bruto: " + vbTab + vbTab + "RD$" + CStr(SueldoBruto))
ListBox1.Items.Add("AFP: " + vbTab + vbTab + vbTab + CStr(AFP) + "%")
ListBox1.Items.Add("ARL: " + vbTab + vbTab + vbTab + CStr(ARL) + "%")
ListBox1.Items.Add("ISR: " + vbTab + vbTab + vbTab + CStr(ISR) + "%")
ListBox1.Items.Add("Total a descontar: " + vbTab + vbTab + "RD$" + CStr(((SueldoBruto * AFP) / 100) + ((SueldoBruto * ARL) / 100) + (ISR)))
ListBox1.Items.Add("Sueldo Neto: " + vbTab + vbTab + "RD$" + CStr(SueldoNexto))
Else
MessageBox.Show("Ingrese sueldo")
End If
End Sub
</pre>
<h3>
<strong>Descripcion del codigo</strong>
</h3>
<p>
Todo el codigo va a estar contenido dentro de la estructura condicional</p>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">
If (Double.TryParse(TextBox1.Text, SueldoBruto)) Then
Else
MessageBox.Show("Ingrese sueldo")
End If
</pre>
<p>
donde el metodo
</p>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">
Double.TryParse(TextBox1.Text, SueldoBruto) </pre>
<p>va a evaluar el valor ingresado por el ususario en la caja de texto,
de ser un valor valido hara la conversion al tipo Double y lo asignara
a la <br />
variable SueldoBruto, luego retornara un valor de true a la condiccion
para que ejecute todo el codigo, de lo contrario enviara un mensaje
para
<br />
que ingrese un valor valido.
<br />
<br />
Tambien podriamos hacer uso de: <a href="https://msdn.microsoft.com/es-es/library/fk6t46tz.aspx">Instrucción Try...Catch...Finally (Visual Basic)</a>. Esta instrucción proporciona una manera de
<br />
controlar algunos o todos los errores posibles que pueden ocurrir en un bloque de código determinado mientras se
<br />
ejecuta el código. Si piensa que se puede producir una excepción determinada en una sección concreta del
<br />
código, incluya éste en un bloque Try y utilice un bloque Catch para conservar el control y tratar la excepción que se produce.</p>
<table style="width: 100%;">
<tr>
<td colspan="2" style="text-align: center"><strong>Descarga</strong></td>
</tr>
<tr>
<td style="text-align: center"><strong><a href="http://1drv.ms/1IiDxHm">C#</a></strong></td>
<td style="text-align: center"><strong><a href="http://1drv.ms/1e6cWiJ">VB</a></strong></td>
</tr>
</table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com0tag:blogger.com,1999:blog-5504661177983996234.post-92177327674870301872012-04-05T14:59:00.001-05:002012-04-07T18:09:11.960-05:00Convertir Numero entre Decimal y Binario<table style="border-collapse: collapse; border-spacing: 0px; width: 100%;">
<tbody>
<tr>
<td>
<strong>Objectivo</strong>
</td>
</tr>
<tr>
<td>
Convertir numeros de Decimales a Binarios y de Binario a Decimal</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<center>
<strong>Codigo C#</strong>
</center>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; "> <strong>private string ConvertDecimalToBinary(string decimaltoconvertto)</strong>
{
#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
}
<strong>private string ConvertBinaryToDecimal(string binarytoconvertto)</strong>
{
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();
}
</pre>
</td>
</tr>
<tr>
<td>
<center>
<strong>Codigo VB</strong>
</center>
</td>
</tr>
<tr>
<td>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;"><strong>Private Function ConvertDecimalToBinary(decimaltoconvertto As String) As String</strong>
'#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
<strong>Private Function ConvertBinaryToDecimal(binarytoconvertto As String) As String</strong>
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</pre>
</td>
</tr>
<tr>
<td>
<strong>Descripcion: </strong>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</tbody>
</table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com2tag:blogger.com,1999:blog-5504661177983996234.post-71971701287155309492012-02-22T16:57:00.000-05:002016-05-02T12:48:47.465-05:00Convertir numero en letra<table style="border-collapse: collapse; border-spacing: 0px; width: 100%;"> <tbody>
<tr> <td><strong>Objetivo</strong> </td></tr>
<tr> <td>Convertir números en su respectiva letras </td></tr>
<tr> <td><br />
<strong>Vista Previa</strong> <br />
<img alt="Blogger" src="https://4k7nla.dm2302.livefilestore.com/y3mJbE2f8PSymGPmWUgoTDxXivdFgkj0EmsMYahD-WuuVi5u6I7vZM7DA1WIeE7hsGblyCo3aIvAMxU5iGK5XTQ4gu3X1uqyx8KgOaJ_cLUnY-BOD08KBXkDSlsCyeuaDabo1qXB4Z7iIQszkRCUNy0SLL411dh3-p5f_W5Vm6SK_g?width=912&height=488&cropmode=none" /> </td></tr>
<tr> <td> </td></tr>
<tr> <td><center>
<strong>Código C#</strong> </center>
</td></tr>
<tr> <td> </td></tr>
<tr> <td><pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">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
/// <summary>
/// Contructor
/// </summary>
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();
}
}
}
}
}
}
}
</pre>
</td></tr>
<tr>
<td colspan="2" style="text-align: center;"><strong>Descarga</strong></td>
</tr>
<tr>
<td ><strong><a href="https://onedrive.live.com/embed?cid=0D6E91641D17F326&resid=D6E91641D17F326%2154320&authkey=AM8-cymhtMcfypQ">Csahrp (C#)</a></strong></td>
<td style="text-align: center;"><strong><a href="">Visual basic (VB)</a></strong></td>
</tr></br></br></br></br>
<tr><td><strong>Descripción: </strong></td></tr>
<tr><td></td></tr>
</tbody></table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com0Santo Domingo, Dominican Republic18.466667 -69.94999999999998918.346188 -70.111361499999987 18.587146 -69.78863849999999tag:blogger.com,1999:blog-5504661177983996234.post-66404389975913027772012-01-24T23:21:00.001-05:002012-01-25T20:31:16.744-05:00Marcar Accion Realizada en DataGridView<table style="border-collapse: collapse; border-spacing: 0px; width: 100%;">
<tbody>
<tr>
<td>
<strong>Objectivo</strong>
</td>
</tr>
<tr>
<td>
Marcar la accion realizada en las filas del DataGridView.</td>
</tr>
<tr>
<td>
<br />
<center>
Vista Previa
<br />
<img alt="Blogger" src="https://public.sn2.livefilestore.com/y1pLrzKhf2_eXlu8iTjfO24Yh_8_V_7TlpCkGMTjqX8epBX08gjZWjmPIKNosM5TOiwKFmXy93t3cNU__G204sIbA/92.png?download&psid=1" />
</center>
</td>
</tr>
<tr>
<td>
<strong>Requisito: </strong>
</td>
</tr>
<tr>
<td>
<ul>
<li>Visual Estudio 2008 o Superior</li>
<li>SQL Server Express 2005 o superior </li>
</ul>
</td>
</tr>
<tr>
<td>
<strong>Para realizar esta practica : </strong>
</td>
</tr>
<tr>
<td>
<ul>
<li>Agregue un projecto tipo WinForm.</li>
<li>Agregar una conexion a la base de datos con la que quiere interactual.<br />
<a href="http://msdn.microsoft.com/es-es/library/fxk9yw1t.aspx">Cómo: Conectarse a los
datos de una base de datos</a>.</li>
<li>Arrastre el objecto de datos con la que quiere trabajar desde la ventana Origen de Datos hacia el diseñador de formulario.<br />
Esto generara los objectos(BindingSource, DataSet, TableAdapter, TableAdapterManager
y el BindingNavigator)<br />
necesario para poder realizar las operaciones(CRUD(Create, Read, Update, Delete))
en la grilla con impacto en la base de datos.</li>
<li>Deshabilito la funcionalidad de eliminacion del control bindingNavigatorDeleteItem
del BindingNavigator.</li>
</ul>
</td>
</tr>
<tr>
<td>
<br />
<center>
<img alt="Blogger" src="https://public.sn2.livefilestore.com/y1ptSuG9YuGO9ob2Ki3NRMSpiLoWfnZVf-JLL15e3HcBLqoOrVBj7fdZ7goNawzkK9jmTKP0doanVoDksOGt-SgiA/95.png?download&psid=1" />
</center>
</td>
</tr>
<tr>
<td>
<ul>
<li>Agregue las imagenes que servirar como marcador para las filas.<br /></li>
</ul>
<center>
<img alt="Blogger" src="https://public.sn2.livefilestore.com/y1ptgW3X8vPte3ojG2fva46t1pExglGsgUfLIKOsj95Xl4Q3K1lcqUK2fmJjpCf522JbPjRlltIvIOlCT_g0HTkEw/97.png?download&psid=1" />
</center>
</td>
</tr>
<tr>
<td>
<ul>
<li>Agregamos una columna de tipo DataGridViewImageColumn en la posicion 0 de la
coleccion de columnas de la grilla y seteamos algunas de sus propiedades<br />
</li>
</ul>
<center>
<img alt="Blogger" src="https://public.sn2.livefilestore.com/y1ptSuG9YuGO9qL-cE-55itrr6dkdsiH9O2TP1FNy0W-iqc1xn-pn60AfuehBlJOdxwAy6ul1xifqnCMsAc8SxbuA/96.png?download&psid=1" />
</center>
</td>
</tr>
<tr>
<td>
<br />
<center>
<strong>Codigo C#</strong></center>
</td>
</tr>
<tr>
<td>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsCS.Formularios
{
public partial class GridMarkedActionForm : Form
{
DataTable table = new DataTable("TB1");
public GridMarkedActionForm()
{
InitializeComponent();
DoColumn("ID", "System.Int32", true, true);
DoColumn("NameAccion", "System.String", false, false);
DoColumn("Image", "System.Byte[]", false, false);
}
#region Metodos de ayuda
private void DoColumn(string name, string type, bool unique, bool isprimary)
{
DataColumn column = new DataColumn(name);
column.DataType = Type.GetType(type);
column.Unique = unique;
table.Columns.Add(column);
if (isprimary)
{
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns[name];
table.PrimaryKey = PrimaryKeyColumns;
}
}
public byte[] ConvertImageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
public Image ConvertByteArrayToImage(int id)
{
MemoryStream ms = new MemoryStream((byte[])table.Rows.Find(id).ItemArray[2]);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
public Image ConvertByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
#endregion Metodos de ayuda
#region EventHandler
private void Form4_Load(object sender, EventArgs e)
{
// TODO: esta línea de código carga datos en la tabla 'testDataSet.T1' Puede moverla o quitarla según sea necesario.
this.t1TableAdapter.Fill(this.testDataSet.T1);
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
row.Cells[0].Value = null;
}
}
private void t1BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
if (table.Rows.Contains(row.Cells[1].Value))
{
if ((table.Rows.Find((int)row.Cells[1].Value).ItemArray[1]).ToString() == "Delete")
{
t1BindingSource.RemoveCurrent();
}
}
}
this.Validate();
this.t1BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.testDataSet);
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
row.Cells[0].Value = null;
}
table.Clear();
}
private void t1BindingSource_ListChanged(object sender, ListChangedEventArgs e)
{
DataRow row = table.NewRow();
switch (e.ListChangedType.ToString())
{
case "ItemChanged":
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Edit";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Edit);
table.Rows.Add(row);
t1DataGridView.CurrentRow.Cells[0].Value = (System.Drawing.Image)Resource1.Edit;
break;
case "ItemAdded":
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Add";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Add);
table.Rows.Add(row);
t1DataGridView.Rows[e.NewIndex].Cells[0].Value = (System.Drawing.Image)Resource1.Add;
break;
// movido al evento clic del boton eliminar, con el objectivo de eliminar esta
// caracteristica del bindingsource e implementarlo de forma manual.
//case "ItemDeleted":
//
// break;
/*
// no implementado
case "ItemMoved":
break;
*/
default:
break;
}
}
private void t1DataGridView_Sorted(object sender, EventArgs e)
{
if (table.Rows.Count > 0)
{
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
if (table.Rows.Contains((Convert.ToInt32(row.Cells[1].Value))))
{
row.Cells[0].Value = ConvertByteArrayToImage((Convert.ToInt32(row.Cells[1].Value)));
}
}
}
}
private void bindingNavigatorDeleteItem_Click_1(object sender, EventArgs e)
{
DataRow row = table.NewRow();
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Delete";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Delete);
table.Rows.Add(row);
t1DataGridView.CurrentRow.Cells[0].Value = (System.Drawing.Image)Resource1.Delete;
}
#endregion EventHandler
}
}
</pre>
</td>
</tr>
<tr>
<td>
<strong>Descripcion: </strong>
</td>
</tr>
<tr>
<td>
<ol>
<li>Creamos una tabla a nivel de clase el cual nos servira como repositorio para almacenar
aqui la acciones realizada en la grilla.</li>
<li>En el constructor del formulario invocamos el metodo DoColumn() el cual crea una
tabla con el siguiente ezquema:
<ul>
<li>Una columna ID de tipo entero el cual servira como PK de la tabla para almacenar
la PK de la grilla</li>
<li>Una columna de tipo string llamada NameAction el cual almacenara el nombre de la
accion realizada en la grilla , Sus posible valores son: Add, Delete, Update</li>
<li>Unaa columna llamada imagen que representa graficamente la accion realizada en la
fila de la grilla
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public GridMarkedActionForm()
{
InitializeComponent();
DoColumn("ID", "System.Int32", true, true);
DoColumn("NameAccion", "System.String", false, false);
DoColumn("Image", "System.Byte[]", false, false);
}</pre>
</li>
</ul>
</li>
<li>El Metodo DoColumn</li>
declara como parameros formales:
<ul>
<li>String que represente el nombre de la columna: name.</li>
<li>String que represente el tipo de dato de la columna: type; Eemplo, "System.String".</li>
<li>Valor Booleano que especifca la columna como unica dentro de la tabla: unique.</li>
<li>Valor Booleano para determinar si la columna a crear sera la PK de la tabla: isprimary.</li>
</ul>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void DoColumn(string name, string type, bool unique, bool isprimary)
{
DataColumn column = new DataColumn(name);
column.DataType = Type.GetType(type);
column.Unique = unique;
table.Columns.Add(column);
if (isprimary)
{
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns[name];
table.PrimaryKey = PrimaryKeyColumns;
}
}</pre>
<li>El Metodo ConvertImageToByteArray() hace la conversion de System.Image a byte[]
para almacenarla en la base de dato</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public byte[] ConvertImageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}</pre>
<li>El Metodo ConvertByteArrayToImage(), recupera el byte[] de la base de dato hace
la conversion a System.Image para asignarselo a la filas de la grilla. </li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">public Image ConvertByteArrayToImage(int id)
{
MemoryStream ms = new MemoryStream((byte[])table.Rows.Find(id).ItemArray[2]);
Image returnImage = Image.FromStream(ms);
return returnImage;
}</pre>
<li>En el Evento Load del formulario nos encargamos de que las filas tenga una imagen
en blanco</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void Form4_Load(object sender, EventArgs e)
{
// TODO: esta línea de código carga datos en la tabla 'testDataSet.T1' Puede moverla o quitarla según sea necesario.
this.t1TableAdapter.Fill(this.testDataSet.T1);
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
row.Cells[0].Value = null;
}
}</pre>
<li>En el Evento Click del BindingNavigatorSaveItem colocamos el siguiente codigo, aqui
es donde implementaremos la accion de eliminacion.:
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void t1BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
if (table.Rows.Contains(row.Cells[1].Value))
{
if ((table.Rows.Find((int)row.Cells[1].Value).ItemArray[1]).ToString() == "Delete")
{
t1BindingSource.RemoveCurrent();
}
}
}
this.Validate();
this.t1BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.testDataSet);
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
row.Cells[0].Value = null;
}
table.Clear();
}</pre>
El cual se encarga de:
<ul>
<li>Procesar cada una de la fila de la grilla para verificar que el valor de la celda
uno(1) el cual corresponde al PK de la grilla este contenido dentro de la tabla
de repositorio; de ser cierto, busco dentro de la coleccion de fila de la tabla
de repositorio la fila que contenga el valor especificado por medio del valor de
la celda uno(1) que coresponde al valor de la PK de la grilla en la fila actual,
descompongo la fila obtenida en cada uno de sus campos o columnas mediante el uso
de <a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ES-ES&k=k(SYSTEM.DATA.DATAROW.ITEMARRAY);k(ITEMARRAY);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true">
DataRow.ItemArray (Propiedad)</a> obtengo en valor del campo o columna uno(1)
que corresponde al NameAction de la tabla y lo comparo con el NameAction == "Delete",
de ser afirmativo procedemos a eliminar la fila actual de la grilla mediante la
invocacion de <a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ES-ES&k=k(SYSTEM.WINDOWS.FORMS.BINDINGNAVIGATOR.DELETEITEM);k(SYSTEM.WINDOWS.FORMS.BINDINGNAVIGATOR);k(VS.PROPERTIES);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN.IMAGE);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN.IMAGE);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN.NAME);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN.NAME);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN);k(SYSTEM.WINDOWS.FORMS.DATAGRIDVIEWIMAGECOLUMN);k(SYSTEM.WINDOWS.FORMS.BINDINGNAVIGATOR);k(DESIGNER_SYSTEM.WINDOWS.FORMS.DESIGN.FORMDOCUMENTDESIGNER);k(VISUALSELECTION);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true">
BindingSource<span xmlns="">.</span>RemoveCurrent (Método)</a>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">foreach (DataGridViewRow row in t1DataGridView.Rows)
{
if (table.Rows.Contains(row.Cells[1].Value))
{
if ((table.Rows.Find((int)row.Cells[1].Value).ItemArray[1]).ToString() == "Delete")
{
t1BindingSource.RemoveCurrent();
}
}
}</pre>
</li>
<li>Valido los controles modificado
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">his.Validate();</pre>
</li>
<li>Aplica los cambios pendientes al origen de datos subyacente
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">this.t1BindingSource.EndEdit();</pre>
</li>
<li>Envio todos los cambios al Dataset
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">this.tableAdapterManager.UpdateAll(this.testDataSet);</pre>
</li>
<li>Limpioi la imagen de la filas
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">foreach (DataGridViewRow row in t1DataGridView.Rows)
{
row.Cells[0].Value = null;
}</pre>
</li>
<li>Elimino los valores de la tabla
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">table.Clear();</pre>
</li>
</ul>
</li>
<li>En el Evento ListChanged del BindingSource colocamos el siguiente codigo:
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void t1BindingSource_ListChanged(object sender, ListChangedEventArgs e)
{
DataRow row = table.NewRow();
switch (e.ListChangedType.ToString())
{
case "ItemChanged":
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Edit";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Edit);
table.Rows.Add(row);
t1DataGridView.CurrentRow.Cells[0].Value = (System.Drawing.Image)Resource1.Edit;
break;
case "ItemAdded":
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Add";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Add);
table.Rows.Add(row);
t1DataGridView.Rows[e.NewIndex].Cells[0].Value = (System.Drawing.Image)Resource1.Add;
break;
// movido al evento clic del boton eliminar, con el objectivo de eliminar esta
// caracteristica del bindingsource e implementarlo de forma manual.
//case "ItemDeleted":
//
// break;
/*
// no implementado
case "ItemMoved":
break;
*/
default:
break;
}
}</pre>
En el cual testeamos <a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ES-ES&k=k(SYSTEM.COMPONENTMODEL.LISTCHANGEDEVENTARGS.LISTCHANGEDTYPE);k(LISTCHANGEDTYPE);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true">
ListChangedEventArgs.ListChangedType (Propiedad) </a> para obtener el tipo
de cambio realizado en el control, creamos una nueva filas con el PK de la grilla,
un NameAction == "a la accion corespondiente", su respectiva imagen y la agregamos
a la coleccion de filas de la tabla de repositorio </li>
<li>En el evento sorted de la grilla nos aseguramo de las imagenes se corespondan no
importando por que columna se ordenen las filas, pero ante confirmamos que nuestra
tabla de repositorio contenga filas esto no garantiza de que si hubo cambio en la
grilla.
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void t1DataGridView_Sorted(object sender, EventArgs e)
{
if (table.Rows.Count > 0)
{
foreach (DataGridViewRow row in t1DataGridView.Rows)
{
if (table.Rows.Contains((Convert.ToInt32(row.Cells[1].Value))))
{
row.Cells[0].Value = ConvertByteArrayToImage((Convert.ToInt32(row.Cells[1].Value)));
}
}
}
}</pre>
</li>
<li>En el evento click del control bindingNavigatorDeleteItem del BindingNavigator,
no eliminamos la filas sino mas bien, la marcamos con la imagen de eliminacion,
pero antes creamos una nueva filas con el PK de la grilla, un NameAction == "Delete",
y la imagen corespondiente a la eliminacion y la agregamos a la coleccion de filas
de la tabla de repositorio
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private void bindingNavigatorDeleteItem_Click_1(object sender, EventArgs e)
{
DataRow row = table.NewRow();
row["ID"] = (int)t1DataGridView.CurrentRow.Cells[1].Value;
row["NameAccion"] = "Delete";
row["Image"] = ConvertImageToByteArray((System.Drawing.Image)Resource1.Delete);
table.Rows.Add(row);
t1DataGridView.CurrentRow.Cells[0].Value = (System.Drawing.Image)Resource1.Delete;
}</pre>
</li>
</ol>
</td>
</tr>
<tr>
<td>
<ul>
<li>Nos restaria Agregar Menu contextuales a las filas de la grilla para deshacer los
cambios realizado por filas separada</li>
<li>Agregar al Toolbox los botones para Deshacer y Reahacer</li>
</ul>
</td>
</tr>
</tbody>
</table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com0tag:blogger.com,1999:blog-5504661177983996234.post-59481292901434024782011-12-27T06:35:00.000-05:002011-12-27T06:35:29.829-05:00Separar cadena delimitada por comas en SQL Server<table style="width: 100%;">
<tbody>
<tr style ="vertical-align: middle; text-align: center">
<td>
<span>
Vista previa<br />
<img alt="Vista Previa" src="https://public.sn2.livefilestore.com/y1pcQdCz_sr8rb4FjRkNmB5pXb6i4l86rkynXBbynboqdn5cv_11f1EHw5OzgilEGpmIMgQh2jo7r0VMMqrYy8xUw/79A.png?download&psid=1" />
</span>
</td>
</tr>
<tr>
<td colspan="2" br />
Requisito</td>
</tr>
<tr>
<td colspan="2">
SQL Server 2008 0 Superior
</td>
</tr>
<tr>
<td colspan="2">
<br />
</td>
</tr>
<tr>
<td colspan="2">
<br />
Objectivo General
</td>
</tr>
<tr>
<td colspan="2">
Crear una consulta que divide una cadena delimitada por comas en diferente valores
</td>
</tr>
<tr>
<td colspan="2">
<br />
</td>
</tr>
<tr>
<td colspan="2">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
USE [Test]]
GO
IF OBJECT_ID('TempTable', N'U') IS NOT NULL
DROP TABLE TempTable
GO
CREATE TABLE TempTable
(
[id] INT IDENTITY(1,1) NOT NULL,
[index] INT,
[valor] NVARCHAR(50) NULL,
[modificado] NVARCHAR(50) NULL,
[original] NVARCHAR(50) NULL
)
GO
DECLARE @ORIGINAL NVARCHAR(50);
DECLARE @MODIFICADO NVARCHAR(50);
DECLARE @job NVARCHAR(50);
DECLARE @INDEX INT = 0;
DECLARE @VALOR NVARCHAR(50) = 0;
SELECT @ORIGINAL = COLUMNB FROM dbo.Table_3 WHERE ID = 7; --19,2,3,14,15,16
INSERT INTO TempTable([valor], [modificado], [original]) VALUES (@VALOR, RTRIM(LTRIM(@ORIGINAL)), RTRIM(LTRIM(@ORIGINAL)))
WHILE ((SELECT LEN([modificado]) from TempTable where id = (select MAX(id) from TempTable)) > 0)
BEGIN
BEGIN TRY
SET @job = (SELECT [modificado] from TempTable where id = (select MAX(id) from TempTable))
SET @VALOR = SUBSTRING(RTRIM(LTRIM(@job)), 1 , CHARINDEX(N',', RTRIM(LTRIM(@job))) - 1);
SET @INDEX = CHARINDEX(N',', @job);
SET @MODIFICADO = SUBSTRING(RTRIM(LTRIM(@job)), @INDEX + 1, LEN(RTRIM(LTRIM(@job))));
IF (((SELECT [index] from TempTable where id = (select MAX(id) from TempTable)) = 0))
BEGIN
INSERT INTO TempTable([index], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
BREAK
END
ELSE
INSERT INTO TempTable([index], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@VALOR)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
CONTINUE
END TRY
BEGIN CATCH
INSERT INTO TempTable([index], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), 0, RTRIM(LTRIM(@ORIGINAL)))
BREAK
END CATCH;
END
GO
</pre>
</td>
</tr>
<tr>
<td colspan="2">
<br />
</td>
</tr>
<tr>
<td colspan="2">
<br />
Descripcion
</td>
</tr>
<tr>
<td colspan="2">
<ol>
<li>Primero verificamos que no exista una tabla que usaremos como tabla temporal Dentro de la base de datos, de existir procedemos a borrarla<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
IF OBJECT_ID('TempTable', N'U') IS NOT NULL
DROP TABLE TempTable
GO</pre>
</li>
<li>Creamos nuestra tabla de datos el cual usaremos como tabla temporal.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
CREATE TABLE TempTable
(
[id] INT IDENTITY(1,1) NOT NULL,
[index de la coma anterior] INT,
[valor] NVARCHAR(50) NULL,
[modificado] NVARCHAR(50) NULL,
[original] NVARCHAR(50) NULL
)
GO
</pre>
</li>
<li>Declaramos la variable que serviran de datos para la tabla asi como para poder ir procesando los valores.
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
DECLARE @ORIGINAL NVARCHAR(50);
DECLARE @MODIFICADO NVARCHAR(50);
DECLARE @job NVARCHAR(50);
DECLARE @INDEX INT = 0;
DECLARE @VALOR NVARCHAR(50) = 0;</pre>
</li>
<li>Extraemos el valor original de la base de datos.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
SELECT @ORIGINAL = COLUMNB FROM dbo.Table_3 WHERE ID = 7;
</pre>
</li>
<li>
Insertamos el valor original a la
tabla temporal. Note que la columna [original]
como la columna [modificado] tendran el mismo valor y la columna [valor]
tendra un valor inicial de cero(0) para la primera fila.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
INSERT INTO TempTable([valor], [modificado], [original]) VALUES (@VALOR, RTRIM(LTRIM(@ORIGINAL)), RTRIM(LTRIM(@ORIGINAL))) </pre>
</li>
<li>
Utilizamos la palabra reservada de control de flujo WHILE, para establecer una
condición para la ejecución repetida de una instrucción o bloque de
instrucciones SQL. Las instrucciones se ejecutan repetidamente siempre que la
condición especificada sea verdadera. Se puede controlar la ejecución de
instrucciones en el bucle WHILE con las palabras clave BREAK y CONTINUE.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
WHILE ((SELECT LEN([modificado]) from TempTable where id = (select MAX(id) from TempTable)) > 0)
BEGIN
BEGIN TRY
SET @job = (SELECT [modificado] from TempTable where id = (select MAX(id) from TempTable))
SET @VALOR = SUBSTRING(RTRIM(LTRIM(@job)), 1 , CHARINDEX(N',', RTRIM(LTRIM(@job))) - 1);
SET @INDEX = CHARINDEX(N',', @job);
SET @MODIFICADO = SUBSTRING(RTRIM(LTRIM(@job)), @INDEX + 1, LEN(RTRIM(LTRIM(@job))));
IF (((SELECT [index de la coma anterior] from TempTable where id = (select MAX(id) from TempTable)) = 0))
BEGIN
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
BREAK
END
ELSE
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@VALOR)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
CONTINUE
END TRY
BEGIN CATCH
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), 0, RTRIM(LTRIM(@ORIGINAL)))
BREAK
END CATCH;
END
GO
</pre>
</li>
<li>
Encerramos el bloque de relevancia dentro de una instrucion TRY....CATCH para
Implementa un mecanismo de control de errores para el procedimiento.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
BEGIN TRY
SET @job = (SELECT [modificado] from TempTable where id = (select MAX(id) from TempTable))
SET @VALOR = SUBSTRING(RTRIM(LTRIM(@job)), 1 , CHARINDEX(N',', RTRIM(LTRIM(@job))) - 1);
SET @INDEX = CHARINDEX(N',', @job);
SET @MODIFICADO = SUBSTRING(RTRIM(LTRIM(@job)), @INDEX + 1, LEN(RTRIM(LTRIM(@job))));
IF (((SELECT [index de la coma anterior] from TempTable where id = (select MAX(id) from TempTable)) = 0))
BEGIN
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
BREAK
END
ELSE
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@VALOR)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
CONTINUE
END TRY
</pre>
</li>
<li>
Dentro del bloque TRY....CATCH seteamos los valores de las variables, para poder
trabajarle, en caso de producirse algun error en el codigo la instrucion pasara
al bloque CATCH donde trataremos los errores. Notese el uso de las funciones:<br />
<ul>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms190329.aspx">LEN(Transact-SQL)</a><br />
</li>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms187751.aspx">MAX(Transact-SQL)</a><br />
</li>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms187748.aspx">SUBSTRING
(Transact-SQL)</a><br />
</li>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms178660.aspx">RTRIM
(Transact-SQL)</a><br />
</li>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms177827.aspx">LTRIM
(Transact-SQL)</a><br />
</li>
<li>
<a href="http://msdn.microsoft.com/es-es/library/ms186323.aspx">CHARINDEX
(Transact-SQL)</a><br />
</li>
</ul>para poder lograr nuestro cometido.
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
SET @job = (SELECT [modificado] from TempTable where id = (select MAX(id) from TempTable))
SET @VALOR = SUBSTRING(RTRIM(LTRIM(@job)), 1 , CHARINDEX(N',', RTRIM(LTRIM(@job))) - 1);
SET @INDEX = CHARINDEX(N',', @job);
SET @MODIFICADO = SUBSTRING(RTRIM(LTRIM(@job)), @INDEX + 1, LEN(RTRIM(LTRIM(@job))));</pre>
</li>
<li>
Luego una instrucion IF...ELSE determina que el valor de la columna [index de la
coma anterior] de la tabla temporar cumpla con la condicion , en caso contrario
se procesa en el bloque ELSE.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
IF (((SELECT [index de la coma anterior] from TempTable where id = (select MAX(id) from TempTable)) = 0))
BEGIN
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
BREAK
END
ELSE
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@VALOR)), RTRIM(LTRIM(@MODIFICADO)), RTRIM(LTRIM(@ORIGINAL)))
CONTINUE
</pre>
</li>
<li>
Por ultimo tenemos el bloque CATCH donde capturamos cualquier anomalia que se
encuentre en el codigo.<br />
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">
BEGIN CATCH
INSERT INTO TempTable([index de la coma anterior], [valor], [modificado], [original]) VALUES (@INDEX, RTRIM(LTRIM(@job)), 0, RTRIM(LTRIM(@ORIGINAL)))
BREAK
END CATCH;
</pre>
</li>
</ol>
</td>
</tr>
</tbody>
</table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com2tag:blogger.com,1999:blog-5504661177983996234.post-86600652112763875172011-08-22T19:51:00.008-05:002012-01-15T09:14:31.787-05:00Metodo Generico<table style="border-collapse: collapse; border-spacing: 0px; width: 100%;">
<tbody>
<tr>
<td><strong>Objectivo</strong>
</td>
</tr>
<tr>
<td>Crear un metodo que no este sujeto a un query especifico y que retorne un control poblado de datos.
</td>
</tr>
<tr>
<td><strong>Requisito:
</strong>
</td>
</tr>
<tr>
<td><ul>
<li>Visual Estudio 2008 o Superior</li>
<li>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 <a href="http://www.codeplex.com/site/search?query=adventureworks&ac=1">
codeplex</a> </li>
<li>Agregar un label al formulario para reflejar el valor selecciona del control</li>
</ul>
</td>
</tr>
<tr>
<td><strong>Nota:
</strong>
</td>
</tr>
<tr>
<td><ul>
<li>Para realizar esta practica agregue u projecto tipo web y pegue este codigo
en el codebehind de la pagina Default.aspx</li>
<li>Este codigo trabaja bien con controles de lista de aplicaciones web y aplicaciones
winform, tales como: </li>
</ul>
</td>
</tr>
<tr>
<td><ol>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.aspx">
CheckBoxList</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx">
DropDownList</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listbox.aspx">
ListBox</a> y </li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobuttonlist.aspx">
RadioButtonList</a></li>
</ol>
</td>
</tr>
<tr>
<td><br />
<br />
<center><strong>Codigo C#</strong></center><strong>
</strong>
</td>
</tr>
<tr>
<td><pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">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
}
</pre>
</td>
</tr>
<tr>
<td><strong>Descripcion:
</strong>
</td>
</tr>
<tr>
<td><ol>
<li>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
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">protected void Page_Load(object sender, EventArgs e)
{
AdventureWorks_DataModel.AdventureWorks_DataEntities db = new AdventureWorks_DataModel.AdventureWorks_DataEntities();
}</pre>
</li>
<li>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:
<ul>
<li>Que como parametro de entrada utilizaremos el tipo Product.</li>
<li>Que como parametro de salida nos retorne un DropDownList para visualizacion los
datos.</li>
</ul>
Y como argumento les estamos pasando:
<ul>
<li>Query que retorna una lista con todas las filas de la base de datos.</li>
<li>"ProductID", como el valor del control ListItems.</li>
<li>"Name", como el valor a mostrar en el control ListItems.</li>
<li>"dd1", como el ID del control.</li>
<li>"Seleccione una Opcion", como Etiqueta del control.</li>
</ul>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true; ">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"));
}</pre>
</li>
<li>Procedemos a la declaracion del metodo que contiene la siguiente firma</li>
<ul>
<li>Un parametro Generico de entrada de Tipo T.</li>
<li>Un parametro Generico de salida de Tipo U.</li>
</ul>
Y como Parametros Formales:
<ul>
<li>Una lista de tipo T.</li>
<li>Un valor para el control ListItems.</li>
<li>Un valor para mostrar en el control ListItems.</li>
<li>El ID del control.</li>
<li>Una etiqueta de apertura.</li>
<li>Y por ultimo restringimos el argumento de tipo a tipo de referencia</li>
</ul>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">private static U ControlBuilder<T, U>(List<T> row, string datavaluefieldname, string datatextfieldname, string id, string Encabezado)
where T : class
where U : class
{
}
</pre>
<li>Pasamos a la implementacion del metodo en donde obtenemos el tipo de valor pasado
para la creacion de nuestra instancia</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">Type ControlToReturnType = typeof(U);</pre>
<li>Creamos una instancia del tipo suministrado, para crear la instancia invocamos el
metodo <a href="http://msdn.microsoft.com/es-do/library/de3dhzwy.aspx">InvokeMember()</a>
del tipo.</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">DropDownList ControlToReturn = (DropDownList)ControlToReturnType.InvokeMember
(
null,
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.CreateInstance,
null,
null,
null
);</pre>
<li>Seteamos las propiedades e instanciamos nuestro manejador de evento</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">ControlToReturn.ID = id;
ControlToReturn.AutoPostBack = true;
ControlToReturn.CausesValidation = false;
ControlToReturn.Width = System.Web.UI.WebControls.Unit.Percentage(100);
ControlToReturn.SelectedIndexChanged += new EventHandler(ControlToReturn_SelectedIndexChanged);
</pre>
<li>Procesamos las filas pasada al metodo mediante el parametro formal "List<T>
Rows" para poder almar nuestro control ListItems</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">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;
}</pre>
<ul>
<li>Descompongo la fila en cada uno de sus columnas o campos mediante
<a href="http://msdn.microsoft.com/es-do/library/system.componentmodel.typedescriptor.getproperties.aspx">
TypeDescriptor<span xmlns="">.</span>GetProperties (Método)</a> y se los agregos a mi coleccion<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(item);;;;
</pre>
</li>
<li>Localizo los campos DataTextField y DataValueField dentro de la coleccion para asignarselo a la
propiedad Text y Value respectivamente del control ListItem</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">System.ComponentModel.PropertyDescriptor MyProperty1 = properties.Find(datatextfieldname, falseSystem.ComponentModel.PropertyDescriptor MyProperty2 = properties.Find(datavaluefieldname, false);
</pre>
<li> Creo mi instancia del control ListItem, pasandole el valor de los campos:
DataTextField y DataValueField mediante
<a href="http://msdn.microsoft.com/es-es/library/system.componentmodel.propertydescriptor.getvalue.aspx">
PropertyDescriptor<span xmlns="">.</span>GetValue (Método)</a>, 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</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">ListItem li = new ListItem();m();
li.Text = MyProperty1.GetValue(item).ToString();
li.Value = MyProperty2.GetValue(item).ToString();
ControlToReturn.Items.Add(li);</pre>
<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 </li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">ListItem EtiquetaApertura = new ListItem();
EtiquetaApertura.Enabled = true;
EtiquetaApertura.Selected = true;
EtiquetaApertura.Value = null;
EtiquetaApertura.Text = Encabezado;
ControlToReturn.Items.Insert(0, EtiquetaApertura);</pre>
</ul>
<li>Retornamos el control</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">return ControlToReturn as U;</pre>
<li>Por ultimo implementamos el metodo manejador para el evento OnSelectedIndexChanged del control retornado</li>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4; toolbar: true;">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;
}</pre>
</ol>
</td>
</tr>
</tbody></table>Angel Rafael Jimenez Guillermohttp://www.blogger.com/profile/15611406358125300721noreply@blogger.com2