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

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Ayuda con un pequeño ejercicio que estoy haciendo en C# con windows form?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ayuda con un pequeño ejercicio que estoy haciendo en C# con windows form?  (Leído 1,709 veces)
Ila26

Desconectado Desconectado

Mensajes: 22


Ver Perfil
Ayuda con un pequeño ejercicio que estoy haciendo en C# con windows form?
« en: 3 Agosto 2014, 18:32 pm »

Saludos...

Quizas para ustedes sea sencillo pero para mi no jajaj estoy aprendiendo :)

Espero que me puedan dar la mano y me expliquen que estaba haciendo mal,se los agradecere de corazon...


La aplicacion que estoy creando le pide al usuario entrar su nombre,apellido y que entre su salario y que pase la informacion a un listbox.
El sueldo tendra una deduccion de un 0.05%

txtname=pepe
txtlastname=lopez
txtsalario=(digamos 450.55)

quiero que en el lstbox me aparezca esa informacion lo unico que el salario sera diferente ya que le quitan el 0.05%

el programa ya lo habia hecho y hacia lo que queria,el problema es que lo quier hacer utilizando CLASES Y METODOS.

Aqui les dejo lo que tengo hecho hasta ahora...

Código
  1. private void button1_Click(object sender, EventArgs e)
  2.        {
  3.            talonary talonaryobj = new talonary();
  4.  
  5.            lsttalonary.Items.Add(talonaryobj.name);
  6.            lsttalonary.Items.Add(talonaryobj.lastname);
  7.            lsttalonary.Items.Add(talonaryobj.salary);
  8.  
  9.  
  10.  
  11.  
  12.        }
  13.  
  14.  

ASI TENGO CONSTRUIDA LA CLASE...
Código
  1. public class talonary
  2.    {
  3.       public string name;
  4.       public string lastname;
  5.       public double salary;
  6.  
  7.  
  8.       public talonary(string name,string lastname,double salary)
  9.       {
  10.           this.name = name;
  11.           this.lastname = lastname;
  12.           this.salary = salary;
  13.       }
  14.  
  15.      double descSalary()
  16.       {
  17.           double salary = 0;
  18.           salary = (salary * 0.05) - salary;
  19.           return salary;
  20.  
  21.       }
  22.  
  23.  


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: Ayuda con un pequeño ejercicio que estoy haciendo en C# con windows form?
« Respuesta #1 en: 3 Agosto 2014, 19:24 pm »

"talonary"?  :xD, menuda invención :P, supongo que intentaste traducir "talonario" al inglés, en ese caso el termino correcto es counterfoil.

Respecto a la Class, ¿podrias especificar en que necesitas ayuda?, eso no me ha quedado claro,
de todas formas si lo que buscas son que te demos consejos, entonces yo te sugiero que guardes la información a modo de base de datos (XML es un formato que me gusta, porque es legible por el humano) y la guardes en un archivo local para guardar los datos de todos los clientes, serializándolo, y acceder cuando precises (deserializando).

Te mostraría un ejemplo, pero sería en VB.NET, de todas formas en MSDN puedes encontrar ejemplos de serialización por XML como este.

Espero que te haya servido de algo,
Saludos.



EDITO:
No estoy acostumbrado a manejar C#, pero aqui tienes unas cuantas mejoras que le hice:

EDITO:
Se me olvidaba comentar que mientras la class siga igual de "simple" realmente no es necesario implementar ISerializable (ni IXmlSerializable), pero mejor tenerlo implementado de manera básica por si piensas hacerle cambios "importantes" en el futuro y lo puedas necesitar, le añadí la implementación de serialización binaria, pero como ya digo todo eso no es necesario ahora mismo, sin implementarlo puedes serializar.

Código
  1. #region Usings
  2.  
  3. using System;
  4. using System.Runtime.Serialization;
  5. using System.Security.Permissions;
  6. using System.Xml.Serialization;
  7. using System.Xml;
  8.  
  9. #endregion
  10.  
  11. /// <summary>
  12. /// Class talonary (or Counterfoil? xD).
  13. /// This class can be serialized.
  14. /// </summary>
  15. [Serializable]
  16. public class talonary : ISerializable, IXmlSerializable
  17. {
  18.  
  19.    #region Properties
  20.  
  21.    /// <summary>
  22.    /// Gets or sets the client name.
  23.    /// </summary>
  24.    /// <value>The name.</value>
  25.    public string name
  26.    {
  27.        get { return this._name; }
  28.        set { this._name = value; }
  29.    }
  30.    private string _name;
  31.  
  32.    /// <summary>
  33.    /// Gets or sets the client surname.
  34.    /// </summary>
  35.    /// <value>The surname.</value>
  36.    public string surname
  37.    {
  38.        get { return this._surname; }
  39.        set { this._surname = value; }
  40.    }
  41.    private string _surname;
  42.  
  43.    /// <summary>
  44.    /// Gets or sets the client salary.
  45.    /// </summary>
  46.    /// <value>The salary.</value>
  47.    public double salary
  48.    {
  49.        get { return this._salary; }
  50.        set { this._salary = value; }
  51.    }
  52.    private double _salary;
  53.  
  54.    /// <summary>
  55.    /// Gets the client salary.
  56.    /// </summary>
  57.    /// <value>The salary.</value>
  58.    public double discountedSalary
  59.    {
  60.        get
  61.        {
  62.            return (this._salary * 0.05D) - this._salary;
  63.        }
  64.    }
  65.  
  66.    #endregion
  67.  
  68.    #region Constructors
  69.  
  70.    /// <summary>
  71.    /// Prevents a default instance of the <see cref="talonary"/> class from being created.
  72.    /// </summary>
  73.    private talonary() { }
  74.  
  75.    /// <summary>
  76.    /// Initializes a new instance of the <see cref="talonary"/> class.
  77.    /// </summary>
  78.    /// <param name="name">Indicates the client name.</param>
  79.    /// <param name="surname">Indicates the client surname.</param>
  80.    /// <param name="salary">Indicates the client salary.</param>
  81.    public talonary(string name,
  82.                    string surname,
  83.                    double salary)
  84.    {
  85.  
  86.        if (name == null)
  87.        {
  88.            throw new ArgumentNullException("name");
  89.        }
  90.  
  91.        this._name = name;
  92.        this._surname = surname;
  93.        this._salary = salary;
  94.    }
  95.  
  96.    #endregion
  97.  
  98.    #region ISerializable implementation | For Binary serialization.
  99.  
  100.    /// <summary>
  101.    /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with the data needed to serialize the target object.
  102.    /// </summary>
  103.    /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> to populate with data.</param>
  104.    /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext" />) for this serialization.</param>
  105.    [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  106.     void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  107.    {
  108.        if (info == null)
  109.        {
  110.            throw new ArgumentNullException("info");
  111.        }
  112.  
  113.        info.AddValue("name", this._name, typeof(string));
  114.        info.AddValue("surname", this._surname, typeof(string));
  115.        info.AddValue("salary", this._salary, typeof(double));
  116.    }
  117.  
  118.    /// <summary>
  119.    /// Initializes a new instance of the <see cref="talonary"/> class.
  120.    /// This constructor is used to deserialize values.
  121.    /// </summary>
  122.    /// <param name="info">The information.</param>
  123.    /// <param name="context">The context.</param>
  124.    protected talonary(SerializationInfo info, StreamingContext context)
  125.    {
  126.        if (info == null)
  127.        {
  128.            throw new ArgumentNullException("info");
  129.        }
  130.  
  131.        this._name = (string)info.GetValue("name", typeof(string));
  132.        this._surname = (string)info.GetValue("surname", typeof(string));
  133.        this._salary = (double)info.GetValue("salary", typeof(double));
  134.    }
  135.  
  136.    #endregion
  137.  
  138.    #region "IXMLSerializable implementation" | For XML serialization.
  139.  
  140.    /// <summary>
  141.    /// This method is reserved and should not be used.
  142.    /// When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method,
  143.    /// and instead, if specifying a custom schema is required, apply the <see cref="T:XmlSchemaProviderAttribute"/> to the class.
  144.    /// </summary>
  145.    /// <returns>
  146.    /// An <see cref="T:Xml.Schema.XmlSchema"/> that describes the XML representation of the object
  147.    /// that is produced by the <see cref="M:IXmlSerializable.WriteXml(Xml.XmlWriter)"/> method
  148.    /// and consumed by the <see cref="M:IXmlSerializable.ReadXml(Xml.XmlReader)"/> method.
  149.    /// </returns>
  150.    public System.Xml.Schema.XmlSchema GetSchema()
  151.    {
  152.        return null;
  153.    }
  154.  
  155.    /// <summary>
  156.    /// Converts an object into its XML representation.
  157.    /// </summary>
  158.    /// <param name="writer">The <see cref="T:Xml.XmlWriter"/> stream to which the object is serialized.</param>
  159.    public void WriteXml(XmlWriter writer)
  160.    {
  161.        writer.WriteElementString("name", this._name);
  162.        writer.WriteElementString("surname", this._surname);
  163.        writer.WriteElementString("salary", Convert.ToString(this._salary));
  164.    }
  165.  
  166.    /// <summary>
  167.    /// Generates an object from its XML representation.
  168.    /// </summary>
  169.    /// <param name="reader">The <see cref="T:Xml.XmlReader"/> stream from which the object is deserialized.</param>
  170.    public void ReadXml(XmlReader reader)
  171.    {
  172.        reader.ReadStartElement(base.GetType().Name);
  173.        this._name = reader.ReadElementContentAsString();
  174.        this._surname = reader.ReadElementContentAsString();
  175.        this._salary = reader.ReadElementContentAsDouble();
  176.    }
  177.  
  178.    #endregion
  179.  
  180. }

EDITO:
No te vendría mal leer esto, sobre la serialización XML: http://support.microsoft.com/kb/316730

Ejemplo:

Código
  1.    Imports System.IO
  2.    Imports System.Xml.Serialization
  3.  
  4.    Public Class TestClass : Inherits form
  5.  
  6.       Private Sub Test_Handler() Handles MyBase.Shown
  7.  
  8.           Dim Clients As New List(Of talonary)
  9.           With Clients
  10.               .Add(New talonary("pedro", "castaño", 10.0R))
  11.               .Add(New talonary("manolo", "ToLoko", 150.0R))
  12.               .Add(New talonary("Elektro", "Zero", Double.MaxValue))
  13.           End With
  14.  
  15.           ' Serialización XML.
  16.           Using Writer As New StreamWriter(".\Clients.xml")
  17.  
  18.               Dim Serializer As New XmlSerializer(Clients.GetType)
  19.               Serializer.Serialize(Writer, Clients)
  20.  
  21.           End Using
  22.  
  23.           ' Deserialización XML.
  24.           Using Reader As New StreamReader(".\Clients.xml")
  25.  
  26.               Dim Serializer As New XmlSerializer(Clients.GetType)
  27.               Dim tmpClients As List(Of talonary) = Serializer.Deserialize(Reader)
  28.  
  29.               For Each Client As talonary In tmpClients
  30.                   MessageBox.Show(Client.name)
  31.               Next
  32.  
  33.           End Using
  34.  
  35.       End Sub
  36.  
  37.    End Class

Traducción al vuelo a C# (no lo he testeado):
Código
  1.    using Microsoft.VisualBasic;
  2.    using System;
  3.    using System.Collections;
  4.    using System.Collections.Generic;
  5.    using System.Data;
  6.    using System.Diagnostics;
  7.    using System.IO;
  8.    using System.Xml.Serialization;
  9.  
  10.    public class TestClass : form
  11.    {
  12.  
  13.  
  14.    private void Test_Handler()
  15.    {
  16.    List<talonary> Clients = new List<talonary>();
  17.    var _with1 = Clients;
  18.    _with1.Add(new talonary("pedro", "castaño", 10.0));
  19.    _with1.Add(new talonary("manolo", "ToLoko", 150.0));
  20.    _with1.Add(new talonary("Elektro", "Zero", double.MaxValue));
  21.  
  22.    // Serialización XML.
  23.    using (StreamWriter Writer = new StreamWriter(".\\Clients.xml")) {
  24.  
  25.    XmlSerializer Serializer = new XmlSerializer(Clients.GetType);
  26.    Serializer.Serialize(Writer, Clients);
  27.  
  28.    }
  29.  
  30.    // Deserialización XML.
  31.    using (StreamReader Reader = new StreamReader(".\\Clients.xml")) {
  32.  
  33.    XmlSerializer Serializer = new XmlSerializer(Clients.GetType);
  34.    List<talonary> tmpClients = Serializer.Deserialize(Reader);
  35.  
  36.    foreach (talonary Client in tmpClients) {
  37.    MessageBox.Show(Client.name);
  38.    }
  39.  
  40.    }
  41.  
  42.    }
  43.    public TestClass()
  44.    {
  45.    Shown += Test_Handler;
  46.    }
  47.  
  48.    }
  49.  
  50.    //=======================================================
  51.    //Service provided by Telerik (www.telerik.com)
  52.    //Conversion powered by NRefactory.
  53.    //Twitter: @telerik
  54.    //Facebook: facebook.com/telerik
  55.    //=======================================================
   
Saludos.


« Última modificación: 3 Agosto 2014, 22:31 pm por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

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