Enter txt file in a datagridview

0

Hi, I have a question about how to send my records from a file with txt extension to a DataGridView work with C ++ in Visual Studio 2012

I enclose an example of how I have the txt file

  

Code, Name, Phone, Mail, Address
  01, Samuel, 222244444, [email protected], city

And I save all these fields to file.txt with textbox and keep them line by line with

  

WriteLine (Here my textbox with its respective variables and delimiter , );
  Example: WriteLine (code-> ToString () + ",") and so on with the others.

The only thing I can not find is to send all my information from the file to the datagridView with those data saved previously. And the other also at the same time, how to add the respective headings of each column, that is, Code, Name, Phone, Mail, Address *

Thank you very much in advance

    
asked by Samuel Mena 07.05.2017 в 04:17
source

1 answer

0

In your file.txt , add a character to the beginning of your header, I will use ; :

  

; Code, Name, Phone, Email, Address

Then, you read all the lines of your file using StreamReader :

StreamReader^ sr = gcnew StreamReader( "fichero.txt" );
try
{
    String^ linea;

    //Creamos un array que almacenará nuestras lineas tratadas
    array<String^>^ lineaArray;

    //Empieza a leer lineas
    while ( linea = sr->ReadLine() )
    {
        //Comprueba que la linea que contiene (;) es de los encabezados.
        if( linea->Contains( ";" )) 
        {
            //Reemplazamos (;) y nos quedaría una cadena (Codigo,Nombre,Telefono,Correo,Direccion)
            String^ encabezados = linea->Replace( ";" , "" );                   

            //con "Split(',')" extraemos cada palabra separada por (,)
            //devolviendo un array: {"Codigo", "Nombre", "Telefono", "Correo", "Direccion"}
            lineaArray = encabezados->Split( ',' )

            //Luego le cambiamos el nombre a las cabeceras de nuestro DataGridView
            //usando "lineaArray"
            columna1->HeaderText = lineaArray[0];
            columna2->HeaderText = lineaArray[1];
            columna3->HeaderText = lineaArray[2];
            columna4->HeaderText = lineaArray[3];
            columna5->HeaderText = lineaArray[4];

            //Continuamos leyendo la siguiente linea
            continue;
        }               

        lineaArray = linea->Split( ',' );
        dataGridView1->Rows->Add( lineaArray );

    }
}
finally
{
    if ( sr )
        delete (IDisposable^)sr;
}

I recommend not using spaces after every , . Otherwise, by doing Split() , it returns a space before each word.

    
answered by 07.05.2017 / 07:43
source