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

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Puedo grabar en un txt varios listbox ?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: Puedo grabar en un txt varios listbox ?  (Leído 6,160 veces)
luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Puedo grabar en un txt varios listbox ?
« en: 4 Febrero 2015, 13:49 pm »

Hola

tengo cuatro listbox

ListBox1
ListBox2
ListBox3
ListBox4

y tengo esta rutina que me grava pero en uno solo y quisera saber si se pueden grabar los cuatro  pero de esta forma

ListBox1    ListBox2      ListBox3     ListBox4
 74             12             25             88
 55             99             33             90
 99             88             44             66


codigo

Código
  1. Dim rutaFichero As String
  2.        Dim i As Integer
  3.  
  4.        rutaFichero = Path.Combine(Application.StartupPath, "Prueba.txt")
  5.        Dim fichero As New IO.StreamWriter(rutaFichero)
  6.        For i = 0 To ListBox1.Items.Count - 1
  7.            fichero.WriteLine(ListBox1.Items(i))
  8.        Next
  9.        fichero.Close()

saludos
Luis


« Última modificación: 4 Febrero 2015, 17:58 pm por luis456 » En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
seba123neo


Desconectado Desconectado

Mensajes: 3.621



Ver Perfil WWW
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #1 en: 4 Febrero 2015, 16:28 pm »

hace lo mismo que estas haciendo pero para los 4 y listo.

pero en vez de poner 4 veces el mismo codigo, create una funcion a la cual la puedas llamar pasandole como parametro el listbox a guardar.


En línea

luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #2 en: 4 Febrero 2015, 16:48 pm »

hace lo mismo que estas haciendo pero para los 4 y listo.

pero en vez de poner 4 veces el mismo codigo, create una funcion a la cual la puedas llamar pasandole como parametro el listbox a guardar.

gracias pero segun entendi lo que me pones es grabar cada ves cada listbox y yo nesecito es gravarlos al mismo tiempo en el mismo txt en ese orden

gracias
Luis
En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
OscarCadenas_91

Desconectado Desconectado

Mensajes: 27


Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #3 en: 4 Febrero 2015, 16:59 pm »

Yo estoy aprendiendo recien, pero talves podrias hacerlo con String.Format

Código
  1. fichero.WriteLine(String.Format("{0}  {1}   {2}   {3}", ListBox1.Items(i), ListBox2.Items(i), ListBox3.Items(i), ListBox4.Items(i)))
En línea

luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #4 en: 4 Febrero 2015, 17:57 pm »

Yo estoy aprendiendo recien, pero talves podrias hacerlo con String.Format

Código
  1. fichero.WriteLine(String.Format("{0}  {1}   {2}   {3}", ListBox1.Items(i), ListBox2.Items(i), ListBox3.Items(i), ListBox4.Items(i)))

Perfecto  gracias mil puntos para ti :)

codigo

Código
  1. Dim rutaFichero As String
  2.        Dim i As Integer
  3.        rutaFichero = Path.Combine(Application.StartupPath, "Prueba.txt")
  4.        Dim fichero As New IO.StreamWriter(rutaFichero)
  5.        For i = 0 To ListBox1.Items.Count - 1
  6.            fichero.WriteLine(String.Format("{0}  {1}   {2}   {3}", ListBox1.Items(i), ListBox2.Items(i), ListBox3.Items(i), ListBox4.Items(i)))
  7.  
  8.         '  fichero.WriteLine(ListBox1.Items(i))
  9.        Next
  10.        fichero.Close()

Luis

En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #5 en: 4 Febrero 2015, 18:42 pm »

Hola Luis

Simplemente podrías serializar los datos en un archivo binario si tu intención es cargarlo de nuevo al programa, es algo muy facil, pero creo que no es el caso lo que quieres hacer, así que esto requiere mucha más escritura.

He escrito este código hardcodeado, optimizado para un conjunto de listas con cantidad de items indefinida en cada lista, y con longitud de item indefinida.

Nota: No lo he testeado mucho, quizás pueda haber agún error en ciertas circunstancias.


Output:
Código:
ListBox1      ListBox2      ListBox3      ListBox4
********      ********      ********      ********
a1qwerty      a2            a3            a4      
qwertyqw                  
erty                      
--------      --------      --------      --------
b1            b2            b3            b4      
--------      --------      --------      --------
c1                          c3                    
--------      --------      --------      --------
                            d3                    
--------      --------      --------      --------


Source:
Código
  1. Imports System.IO
  2. Imports System.Text
  3.  
  4. Public Class TestForm
  5.  
  6.    Private Sub Test() Handles Button1.Click
  7.  
  8.        Dim lbs As ListBox() = {ListBox1, ListBox2, ListBox3, ListBox4}
  9.        Dim spacing As Integer = 6 ' The horizontal spacing between columns.
  10.        Dim filaPath As String = Path.Combine(Application.StartupPath, "Test.txt")
  11.        Dim item1Parts As IEnumerable(Of String) = {}
  12.        Dim item2Parts As IEnumerable(Of String) = {}
  13.        Dim item3Parts As IEnumerable(Of String) = {}
  14.        Dim item4Parts As IEnumerable(Of String) = {}
  15.        Dim maxItemCount As Integer
  16.        Dim maxItemPartCount As Integer
  17.        Dim sb As New StringBuilder
  18.  
  19.        ' Get the max item count in listboxes.
  20.        maxItemCount = (From lb As ListBox In lbs
  21.                                       Order By lb.Items.Count Descending
  22.                                       Select lb.Items.Count).First
  23.  
  24.        ' Write column names.
  25.        sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  26.                      New String(" "c, spacing),
  27.                      lbs(0).Name, lbs(1).Name,
  28.                      lbs(2).Name, lbs(3).Name))
  29.  
  30.        ' Write column separator.
  31.        sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  32.                      New String(" "c, spacing),
  33.                      New String("*"c, lbs(0).Name.Length),
  34.                      New String("*"c, lbs(1).Name.Length),
  35.                      New String("*"c, lbs(2).Name.Length),
  36.                      New String("*"c, lbs(3).Name.Length)))
  37.  
  38.        ' Iterate listbox items.
  39.        For index As Integer = 0 To (maxItemCount - 1)
  40.  
  41.            ' If item at index exist...
  42.            If lbs(0).Items.Count > index Then
  43.                item1Parts = SplitByLength(lbs(0).Items(index).ToString, lbs(0).Name.Length)
  44.            End If
  45.  
  46.            If lbs(1).Items.Count > index Then
  47.                item2Parts = SplitByLength(lbs(1).Items(index).ToString, lbs(1).Name.Length)
  48.            End If
  49.  
  50.            If lbs(2).Items.Count > index Then
  51.                item3Parts = SplitByLength(lbs(2).Items(index).ToString, lbs(2).Name.Length)
  52.            End If
  53.  
  54.            If lbs(3).Items.Count > index Then
  55.                item4Parts = SplitByLength(lbs(3).Items(index).ToString, lbs(3).Name.Length)
  56.            End If
  57.  
  58.            If (item1Parts.Count > 1) OrElse
  59.               (item2Parts.Count > 1) OrElse
  60.               (item3Parts.Count > 1) OrElse
  61.               (item4Parts.Count > 1) Then
  62.  
  63.                ' Get the max item count in itemParts.
  64.                maxItemPartCount = (From col As IEnumerable(Of String)
  65.                                    In {item1Parts, item2Parts, item3Parts, item4Parts}
  66.                                    Order By col.Count Descending
  67.                                    Select col.Count).First
  68.  
  69.                For x As Integer = 0 To (maxItemPartCount - 1)
  70.  
  71.                    ' Write multiple items rows.
  72.                    sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  73.                                      New String(" "c, spacing),
  74.                                      If(item1Parts.Count <= x, String.Empty,
  75.                                         item1Parts(x) & New String(" "c, lbs(0).Name.Length - item1Parts(x).Length)),
  76.                                      If(item2Parts.Count <= x, String.Empty,
  77.                                         item2Parts(x) & New String(" "c, lbs(1).Name.Length - item2Parts(x).Length)),
  78.                                      If(item3Parts.Count <= x, String.Empty,
  79.                                         item3Parts(x) & New String(" "c, lbs(2).Name.Length - item3Parts(x).Length)),
  80.                                      If(item4Parts.Count <= x, String.Empty,
  81.                                         item4Parts(x) & New String(" "c, lbs(3).Name.Length - item4Parts(x).Length))))
  82.                Next
  83.  
  84.            Else
  85.                ' Write simgle items row.
  86.                sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  87.                                  New String(" "c, spacing),
  88.                                  If(lbs(0).Items.Count <= index,
  89.                                     String.Empty & New String(" "c, lbs(0).Name.Length),
  90.                                     item1Parts.First & New String(" "c, lbs(0).Name.Length - item1Parts.First.Length)),
  91.                                  If(lbs(1).Items.Count <= index,
  92.                                     String.Empty & New String(" "c, lbs(1).Name.Length),
  93.                                     item2Parts.First & New String(" "c, lbs(1).Name.Length - item2Parts.First.Length)),
  94.                                  If(lbs(2).Items.Count <= index,
  95.                                     String.Empty & New String(" "c, lbs(2).Name.Length),
  96.                                     item3Parts.First & New String(" "c, lbs(2).Name.Length - item3Parts.First.Length)),
  97.                                  If(lbs(3).Items.Count <= index,
  98.                                     String.Empty & New String(" "c, lbs(3).Name.Length),
  99.                                     item4Parts.First & New String(" "c, lbs(3).Name.Length - item4Parts.First.Length))))
  100.  
  101.            End If
  102.  
  103.            ' Write horizontal grid.
  104.            sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  105.                          New String(" "c, spacing),
  106.                          New String("-"c, lbs(0).Name.Length),
  107.                          New String("-"c, lbs(1).Name.Length),
  108.                          New String("-"c, lbs(2).Name.Length),
  109.                          New String("-"c, lbs(3).Name.Length)))
  110.  
  111.        Next index
  112.  
  113.        File.WriteAllText(filaPath, sb.ToString, Encoding.Default)
  114.        sb.Clear()
  115.        Process.Start(filaPath)
  116.  
  117.    End Sub
  118.  
  119.    ' Split By Length
  120.    ' By Elektro
  121.    '
  122.    ''' <summary>
  123.    ''' Splits a string by the specified character length.
  124.    ''' </summary>
  125.    ''' <param name="str">The string to split.</param>
  126.    ''' <param name="length">The character length.</param>
  127.    ''' <returns>IEnumerable(Of System.String).</returns>
  128.    Private Function SplitByLength(ByVal str As String,
  129.                                   ByVal length As Integer) As IEnumerable(Of String)
  130.  
  131.        Dim stringParts As New List(Of String)
  132.  
  133.        If str.Length > length Then
  134.  
  135.            Do Until str.Length <= length
  136.                stringParts.Add(str.Substring(0, length))
  137.                str = str.Remove(0, length)
  138.            Loop
  139.  
  140.            ' Add the last missing part (if any).
  141.            If Not String.IsNullOrEmpty(str) Then
  142.                stringParts.Add(str)
  143.            End If
  144.  
  145.        Else
  146.            stringParts.Add(str)
  147.  
  148.        End If
  149.  
  150.        Return stringParts
  151.  
  152.    End Function
  153.  
  154. End Class
« Última modificación: 4 Febrero 2015, 18:45 pm por Eleкtro » En línea

seba123neo


Desconectado Desconectado

Mensajes: 3.621



Ver Perfil WWW
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #6 en: 4 Febrero 2015, 19:13 pm »

¿ tiene que quedar asi en ese formato si o si ?

porque si es grsabarlo y despues recuperarlo, podes usar simplemente un archivo .ini, es muy facil grabarlo y despues volver a recuperar los datos.
En línea

luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #7 en: 4 Febrero 2015, 19:50 pm »

¿ tiene que quedar asi en ese formato si o si ?

porque si es grsabarlo y despues recuperarlo, podes usar simplemente un archivo .ini, es muy facil grabarlo y despues volver a recuperar los datos.

de gravarlo tiene que ser asi ya que debo imprimir el txt para otros menesteres pero con el codigo que me suministra  nuestro  amigo Elektro que por cierto es mas largo que mi propio programa jajajja me sobra :)

Gracias a todos

Luis

En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #8 en: 4 Febrero 2015, 20:07 pm »

Hola Luis

Simplemente podrías serializar los datos en un archivo binario si tu intención es cargarlo de nuevo al programa, es algo muy facil, pero creo que no es el caso lo que quieres hacer, así que esto requiere mucha más escritura.

He escrito este código hardcodeado, optimizado para un conjunto de listas con cantidad de items indefinida en cada lista, y con longitud de item indefinida.

Nota: No lo he testeado mucho, quizás pueda haber agún error en ciertas circunstancias.


Output:
Código:
ListBox1      ListBox2      ListBox3      ListBox4
********      ********      ********      ********
a1qwerty      a2            a3            a4      
qwertyqw                  
erty                      
--------      --------      --------      --------
b1            b2            b3            b4      
--------      --------      --------      --------
c1                          c3                    
--------      --------      --------      --------
                            d3                    
--------      --------      --------      --------


Source:
Código
  1. Imports System.IO
  2. Imports System.Text
  3.  
  4. Public Class TestForm
  5.  
  6.    Private Sub Test() Handles Button1.Click
  7.  
  8.        Dim lbs As ListBox() = {ListBox1, ListBox2, ListBox3, ListBox4}
  9.        Dim spacing As Integer = 6 ' The horizontal spacing between columns.
  10.        Dim filaPath As String = Path.Combine(Application.StartupPath, "Test.txt")
  11.        Dim item1Parts As IEnumerable(Of String) = {}
  12.        Dim item2Parts As IEnumerable(Of String) = {}
  13.        Dim item3Parts As IEnumerable(Of String) = {}
  14.        Dim item4Parts As IEnumerable(Of String) = {}
  15.        Dim maxItemCount As Integer
  16.        Dim maxItemPartCount As Integer
  17.        Dim sb As New StringBuilder
  18.  
  19.        ' Get the max item count in listboxes.
  20.        maxItemCount = (From lb As ListBox In lbs
  21.                                       Order By lb.Items.Count Descending
  22.                                       Select lb.Items.Count).First
  23.  
  24.        ' Write column names.
  25.        sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  26.                      New String(" "c, spacing),
  27.                      lbs(0).Name, lbs(1).Name,
  28.                      lbs(2).Name, lbs(3).Name))
  29.  
  30.        ' Write column separator.
  31.        sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  32.                      New String(" "c, spacing),
  33.                      New String("*"c, lbs(0).Name.Length),
  34.                      New String("*"c, lbs(1).Name.Length),
  35.                      New String("*"c, lbs(2).Name.Length),
  36.                      New String("*"c, lbs(3).Name.Length)))
  37.  
  38.        ' Iterate listbox items.
  39.        For index As Integer = 0 To (maxItemCount - 1)
  40.  
  41.            ' If item at index exist...
  42.            If lbs(0).Items.Count > index Then
  43.                item1Parts = SplitByLength(lbs(0).Items(index).ToString, lbs(0).Name.Length)
  44.            End If
  45.  
  46.            If lbs(1).Items.Count > index Then
  47.                item2Parts = SplitByLength(lbs(1).Items(index).ToString, lbs(1).Name.Length)
  48.            End If
  49.  
  50.            If lbs(2).Items.Count > index Then
  51.                item3Parts = SplitByLength(lbs(2).Items(index).ToString, lbs(2).Name.Length)
  52.            End If
  53.  
  54.            If lbs(3).Items.Count > index Then
  55.                item4Parts = SplitByLength(lbs(3).Items(index).ToString, lbs(3).Name.Length)
  56.            End If
  57.  
  58.            If (item1Parts.Count > 1) OrElse
  59.               (item2Parts.Count > 1) OrElse
  60.               (item3Parts.Count > 1) OrElse
  61.               (item4Parts.Count > 1) Then
  62.  
  63.                ' Get the max item count in itemParts.
  64.                maxItemPartCount = (From col As IEnumerable(Of String)
  65.                                    In {item1Parts, item2Parts, item3Parts, item4Parts}
  66.                                    Order By col.Count Descending
  67.                                    Select col.Count).First
  68.  
  69.                For x As Integer = 0 To (maxItemPartCount - 1)
  70.  
  71.                    ' Write multiple items rows.
  72.                    sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  73.                                      New String(" "c, spacing),
  74.                                      If(item1Parts.Count <= x, String.Empty,
  75.                                         item1Parts(x) & New String(" "c, lbs(0).Name.Length - item1Parts(x).Length)),
  76.                                      If(item2Parts.Count <= x, String.Empty,
  77.                                         item2Parts(x) & New String(" "c, lbs(1).Name.Length - item2Parts(x).Length)),
  78.                                      If(item3Parts.Count <= x, String.Empty,
  79.                                         item3Parts(x) & New String(" "c, lbs(2).Name.Length - item3Parts(x).Length)),
  80.                                      If(item4Parts.Count <= x, String.Empty,
  81.                                         item4Parts(x) & New String(" "c, lbs(3).Name.Length - item4Parts(x).Length))))
  82.                Next
  83.  
  84.            Else
  85.                ' Write simgle items row.
  86.                sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  87.                                  New String(" "c, spacing),
  88.                                  If(lbs(0).Items.Count <= index,
  89.                                     String.Empty & New String(" "c, lbs(0).Name.Length),
  90.                                     item1Parts.First & New String(" "c, lbs(0).Name.Length - item1Parts.First.Length)),
  91.                                  If(lbs(1).Items.Count <= index,
  92.                                     String.Empty & New String(" "c, lbs(1).Name.Length),
  93.                                     item2Parts.First & New String(" "c, lbs(1).Name.Length - item2Parts.First.Length)),
  94.                                  If(lbs(2).Items.Count <= index,
  95.                                     String.Empty & New String(" "c, lbs(2).Name.Length),
  96.                                     item3Parts.First & New String(" "c, lbs(2).Name.Length - item3Parts.First.Length)),
  97.                                  If(lbs(3).Items.Count <= index,
  98.                                     String.Empty & New String(" "c, lbs(3).Name.Length),
  99.                                     item4Parts.First & New String(" "c, lbs(3).Name.Length - item4Parts.First.Length))))
  100.  
  101.            End If
  102.  
  103.            ' Write horizontal grid.
  104.            sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}",
  105.                          New String(" "c, spacing),
  106.                          New String("-"c, lbs(0).Name.Length),
  107.                          New String("-"c, lbs(1).Name.Length),
  108.                          New String("-"c, lbs(2).Name.Length),
  109.                          New String("-"c, lbs(3).Name.Length)))
  110.  
  111.        Next index
  112.  
  113.        File.WriteAllText(filaPath, sb.ToString, Encoding.Default)
  114.        sb.Clear()
  115.        Process.Start(filaPath)
  116.  
  117.    End Sub
  118.  
  119.    ' Split By Length
  120.    ' By Elektro
  121.    '
  122.    ''' <summary>
  123.    ''' Splits a string by the specified character length.
  124.    ''' </summary>
  125.    ''' <param name="str">The string to split.</param>
  126.    ''' <param name="length">The character length.</param>
  127.    ''' <returns>IEnumerable(Of System.String).</returns>
  128.    Private Function SplitByLength(ByVal str As String,
  129.                                   ByVal length As Integer) As IEnumerable(Of String)
  130.  
  131.        Dim stringParts As New List(Of String)
  132.  
  133.        If str.Length > length Then
  134.  
  135.            Do Until str.Length <= length
  136.                stringParts.Add(str.Substring(0, length))
  137.                str = str.Remove(0, length)
  138.            Loop
  139.  
  140.            ' Add the last missing part (if any).
  141.            If Not String.IsNullOrEmpty(str) Then
  142.                stringParts.Add(str)
  143.            End If
  144.  
  145.        Else
  146.            stringParts.Add(str)
  147.  
  148.        End If
  149.  
  150.        Return stringParts
  151.  
  152.    End Function
  153.  
  154. End Class


Haberme leido la mente no hubiera sido tan asombrosamente . Mil puntos para ti tambien elektro  gracias menudo codigo :) Funciona de maravilla

Luis


En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: Puedo grabar en un txt varios listbox ?
« Respuesta #9 en: 5 Febrero 2015, 11:58 am »

Pero claro ya Elektro se estaria preguntando que esta ves fue facil  ;)

 pero no jejejje te tengo una pregunta ? se puede cambiar esto y poner otro nombre por ejemplo



 ListBox1      ListBox2      ListBox3      ListBox4
********      ********      ********      ********

y poner


resultado 1    resultado2   resultado3   resultado4
********     ********   ********    ********

Saludos
Luis



En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Grabar en un dvd varios vcd???
Software
guerrerito 1 2,499 Último mensaje 28 Septiembre 2004, 03:47 am
por Songoku
grabar varios AVI en un dvd
Multimedia
martionote 4 2,429 Último mensaje 18 Noviembre 2004, 06:05 am
por Songoku
Grabar varios DVD en un DVD-R
Multimedia
Vicente 1 6,003 Último mensaje 10 Febrero 2005, 07:03 am
por Songoku
grabar varios avi en un dvd
Software
rulbury 3 8,737 Último mensaje 23 Mayo 2005, 13:44 pm
por Songoku
unir varios listbox en Visual Basic 6.0
Programación Visual Basic
kenrigls 3 2,620 Último mensaje 8 Abril 2014, 21:57 pm
por 79137913
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines