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

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Ayuda] Listbox , identificado y guardado de datos en C#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Ayuda] Listbox , identificado y guardado de datos en C#  (Leído 2,443 veces)
laut3n

Desconectado Desconectado

Mensajes: 4


Ver Perfil
[Ayuda] Listbox , identificado y guardado de datos en C#
« en: 17 Enero 2015, 07:52 am »

Buenas a todos , como andan ?

Bueno , les explico el problema que tengo actualmente.

Estoy trabado en el medio de mi proyecto por lo siguiente : Resulta que tengo que guardar unas "Preguntas" y unas "Respuestas" en un listbox (Sistema dinamico , el usuario podria agregar o quitar preguntas) , no se como guardar el texto de la listbox pero ya se me va a ocurrir , lo que me complica es esto : Como voy a identificar cada Pregunta y su correspondientes respuestas , EJ:

Pregunta : Cuantas patas tiene un perro?
Respuesta : 4

Alguno que otro va a saltar diciendo que lo haga a mano por codigo pero mi idea es que sea dinamico y que se almacene en el listbox.

Saludos!


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [Ayuda] Listbox , identificado y guardado de datos en C#
« Respuesta #1 en: 17 Enero 2015, 10:14 am »

Alguno que otro va a saltar diciendo que lo haga a mano por codigo pero mi idea es que sea dinamico y que se almacene en el listbox.

No me ha quedado muy claro lo que quieres hacer, ¿ambos datos, preguntas y respuestas, quieres mostrarlos en un ListBox?, ¿o solo quieres mostrar las preguntas y ligar las respuestas a cada pregunta?.

En el primer caso, un ListBox no está diseñado para almacenar/mostrar parejas de items, así que si pretendes mostrar ambos datos eso significa que le estás dándole el enfoque erroneo a tu aplicación, en su lugar puedes crear tu propio control, o utilizar un ListView por ejemplo, con 2 columnas, una para mostrar preguntas y en la otra respuestas.

En el segundo caso, una solución sería almacenar las preguntas y respuestas en una colección se strings, o por ejemplo un KeyValuePair o una Tupla (entre otras), o tambiénbien puedes crear tu propio Type, ejemplo:


VB.Net:
Código
  1.    ''' <summary>
  2.    ''' Implements a kind of Question/Answer KeyValuePair.
  3.    ''' This class cannot be inherited.
  4.    ''' </summary>
  5.    Public NotInheritable Class QA
  6.  
  7.        ''' <summary>
  8.        ''' Gets the question.
  9.        ''' </summary>
  10.        ''' <value>The question.</value>
  11.        ReadOnly Property Question As String
  12.            Get
  13.                Return Me.mQuestion
  14.            End Get
  15.        End Property
  16.        Private mQuestion As String
  17.  
  18.        ''' <summary>
  19.        ''' Gets the answer.
  20.        ''' </summary>
  21.        ''' <value>The answer.</value>
  22.        ReadOnly Property Answer As String
  23.            Get
  24.                Return Me.mAnswer
  25.            End Get
  26.        End Property
  27.        Private mAnswer As String
  28.  
  29.        ''' <summary>
  30.        ''' Initializes a new instance of the <see cref="QA"/> class.
  31.        ''' </summary>
  32.        ''' <param name="question">The question.</param>
  33.        ''' <param name="answer">The answer.</param>
  34.        ''' <exception cref="System.ArgumentNullException">
  35.        ''' question;value cannot be empty.
  36.        ''' or
  37.        ''' answer;value cannot be empty.
  38.        ''' </exception>
  39.        Public Sub New(ByVal question As String, ByVal answer As String)
  40.  
  41.            If String.IsNullOrEmpty(question) Then
  42.                Throw New ArgumentNullException("question", "value cannot be empty.")
  43.  
  44.            ElseIf String.IsNullOrEmpty(answer) Then
  45.                Throw New ArgumentNullException("answer", "value cannot be empty.")
  46.  
  47.            Else
  48.                Me.mQuestion = question
  49.                Me.mAnswer = answer
  50.  
  51.            End If
  52.  
  53.        End Sub
  54.  
  55.        ''' <summary>
  56.        ''' Prevents a default instance of the <see cref="QA"/> class from being created.
  57.        ''' </summary>
  58.        Private Sub New()
  59.        End Sub
  60.  
  61.    End Class
+
Código
  1. Public Class TestForm
  2.  
  3.    ''' <summary>
  4.    ''' The Question/Answer list.
  5.    ''' </summary>
  6.    Public ReadOnly QAlist As New List(Of QA) From {
  7.        New QA(question:="pregunta1", answer:="7"),
  8.        New QA(question:="pregunta2", answer:="9"),
  9.        New QA(question:="pregunta3", answer:="5")
  10.    }
  11.  
  12.    ''' <summary>
  13.    ''' Handles the Load event of the TestForm form.
  14.    ''' </summary>
  15.    Private Sub TestForm_Load(ByVal sender As Object, ByVal e As EventArgs) _
  16.    Handles MyBase.Load
  17.  
  18.        ' Add the questions into Listbox.
  19.        Me.ListBox1.Items.AddRange((From qa As QA In QAlist Select qa.Question).ToArray)
  20.  
  21.    End Sub
  22.  
  23.    ''' <summary>
  24.    ''' Handles the SelectedIndexChanged event of the ListBox1 control.
  25.    ''' </summary>
  26.    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
  27.    Handles ListBox1.SelectedIndexChanged
  28.  
  29.        Dim lb As ListBox = DirectCast(sender, ListBox)
  30.        If Not lb.SelectionMode = SelectionMode.One Then
  31.            Throw New NotImplementedException("SelectionMode is not implemented.")
  32.        End If
  33.  
  34.        Dim qa As QA = QAlist.Find(Function(x As QA) x.Question.Equals(lb.SelectedItem.ToString))
  35.  
  36.        Debug.WriteLine(String.Format("Q: {0}", qa.Question))
  37.        Debug.WriteLine(String.Format("A: {0}", qa.Answer))
  38.        Debug.WriteLine(String.Empty)
  39.  
  40.    End Sub
  41.  
  42. End Class

CSharp:
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.  
  8. /// <summary>
  9. /// Implements a kind of Question/Answer KeyValuePair.
  10. /// This class cannot be inherited.
  11. /// </summary>
  12. public sealed class QA
  13. {
  14.  
  15. /// <summary>
  16. /// Gets the question.
  17. /// </summary>
  18. /// <value>The question.</value>
  19. public string Question {
  20. get { return this.mQuestion; }
  21. }
  22. private string mQuestion;
  23.  
  24. /// <summary>
  25. /// Gets the answer.
  26. /// </summary>
  27. /// <value>The answer.</value>
  28. public string Answer {
  29. get { return this.mAnswer; }
  30. }
  31. private string mAnswer;
  32.  
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="QA"/> class.
  35. /// </summary>
  36. /// <param name="question">The question.</param>
  37. /// <param name="answer">The answer.</param>
  38. /// <exception cref="System.ArgumentNullException">
  39. /// question;value cannot be empty.
  40. /// or
  41. /// answer;value cannot be empty.
  42. /// </exception>
  43. public QA(string question, string answer)
  44. {
  45. if (string.IsNullOrEmpty(question)) {
  46. throw new ArgumentNullException("question", "value cannot be empty.");
  47.  
  48. } else if (string.IsNullOrEmpty(answer)) {
  49. throw new ArgumentNullException("answer", "value cannot be empty.");
  50.  
  51. } else {
  52. this.mQuestion = question;
  53. this.mAnswer = answer;
  54.  
  55. }
  56.  
  57. }
  58.  
  59. /// <summary>
  60. /// Prevents a default instance of the <see cref="QA"/> class from being created.
  61. /// </summary>
  62. private QA()
  63. {
  64. }
  65.  
  66. }
  67.  
  68. //=======================================================
  69. //Service provided by Telerik (www.telerik.com)
  70. //=======================================================
+
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.  
  8. public class TestForm
  9. {
  10.  
  11. /// <summary>
  12. /// The Question/Answer list.
  13. /// </summary>
  14. public readonly List<QA> QAlist = new List<QA> {
  15. new QA(question: "pregunta1", answer: "7"),
  16. new QA(question: "pregunta2", answer: "9"),
  17. new QA(question: "pregunta3", answer: "5")
  18.  
  19. };
  20.  
  21. /// <summary>
  22. /// Handles the Load event of the TestForm form.
  23. /// </summary>
  24. private void TestForm_Load(object sender, EventArgs e)
  25. {
  26. // Add the questions into Listbox.
  27. this.ListBox1.Items.AddRange((from qa in QAlistqa.Question).ToArray);
  28.  
  29. }
  30.  
  31. /// <summary>
  32. /// Handles the SelectedIndexChanged event of the ListBox1 control.
  33. /// </summary>
  34. private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
  35. {
  36. ListBox lb = (ListBox)sender;
  37. if (!(lb.SelectionMode == SelectionMode.One)) {
  38. throw new NotImplementedException("SelectionMode is not implemented.");
  39. }
  40.  
  41. QA qa = QAlist.Find((QA x) => x.Question.Equals(lb.SelectedItem.ToString));
  42.  
  43. Debug.WriteLine(string.Format("Q: {0}", qa.Question));
  44. Debug.WriteLine(string.Format("A: {0}", qa.Answer));
  45. Debug.WriteLine(string.Empty);
  46.  
  47. }
  48. public TestForm()
  49. {
  50. Load += TestForm_Load;
  51. }
  52.  
  53. }
  54.  
  55. //=======================================================
  56. //Service provided by Telerik (www.telerik.com)
  57. //=======================================================



Debug Output:
Código:
Q: pregunta1
A: 7

Q: pregunta2
A: 9

Q: pregunta3
A: 5


« Última modificación: 17 Enero 2015, 10:28 am por Eleкtro » En línea

laut3n

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: [Ayuda] Listbox , identificado y guardado de datos en C#
« Respuesta #2 en: 18 Enero 2015, 05:03 am »

Muchisimas gracias , logre hacer mi sistema que tenia en mente basandome en tu respuesta.

Muchas gracias y saludos!  ;D
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Reproducir datos de listbox
Programación Visual Basic
bautistasbr 1 1,891 Último mensaje 5 Septiembre 2006, 01:36 am
por yeikos
combinar listbox con base de datos
Programación Visual Basic
satan69 6 2,481 Último mensaje 11 Enero 2007, 22:11 pm
por satan69
php recepcion de datos y guardado en mysql, no encuentro el error « 1 2 »
PHP
Pirat3net 10 4,673 Último mensaje 7 Abril 2012, 13:04 pm
por |Miguel|
Datos desde SQL a ListBox
.NET (C#, VB.NET, ASP)
el_cantante 6 6,259 Último mensaje 31 Mayo 2012, 01:20 am
por HdM
Ayuda guardado de archivo « 1 2 »
Programación C/C++
novatus84 11 4,746 Último mensaje 27 Noviembre 2014, 18:22 pm
por novatus84
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines