Background:
I have a "Windows Forms" desktop application that basically queries information from a database in MS-Access to generate a text file.
I'm using spaces so the text "in text file" looks centered.
Example:
If I want the following text to be centered:
string titulo = "Restaurante Napolitano La 26";
MessageBox.Show(titulo);
//Restaurante Napolitano La 26
I use PadRight or PadLeft , to get this result:
string titulo = "Restaurante Napolitano La 26";
titulo = titulo.PadLeft(20, ' ');
MessageBox.Show(titulo);
// Restaurante Napolitano La 26
But I don't understand why it is not adding the spaces.
This is a sample of the code I am using.
// Voy concatenando el texto de la tabla.
string mensaje_a_imprimir = "";
// Valor de la fila-columna. Para este ejemplo, será el valor de la columna "RestauranteName".
string valor_a_imprimir = "";
// Variable que contiene estos datos:
DataTable tbl_result_sql;
-------------------------------------------------------------------------
| RestaurantName | NIT | Ciudad | RegimenComun |
|-------------------------------|---------- |-----------|---------------|
| Restaurante Napolitano La 26 | NIT: 123 | City1 | Regimen Comun |
-------------------------------------------------------------------------
// Asigno el valor a la variable.
valor_a_imprimir = tbl_result_sql.Rows[0][0].ToString().Trim();
// Lo asigno nuevamente, pero con los espacios adicionales.
// El número "40" se debe a que el ancho de la información es de máximo 40 caracteres "con espacios".
valor_a_imprimir = valor_a_imprimir.PadLeft((40 - valor_a_imprimir.Length), '.');
// Este es el contenido que tendrá el archivo de texto.
mensaje_a_imprimir += valor_a_imprimir + "\r\n";
// Generar archivo de texto.
File.WriteAllText(@"C:\Nueva Carpeta\TextoPrueba.txt", mensaje_a_imprimir);
My questions are:
- Why am I not getting the expected results when using PadRight / PadLeft?
- In case there is another alternative, what can I use to add spaces to a string that will allow me to center the text? 1
1 I hope to avoid doing complex calculations "because in the end, the text file is a sample of how it will look before it is printed".
padleft's parameter is the length of the string that adds the missing characters to reach that length either to the left or to the right.
to make it work as you want you have to add the actual length of the string:
I don't know what you want to do here:
this won't do anything, if you want to limit the length of the string you should use substr and not pad