Problem with formatting a string using String.Format in C #

I need to print a line in a message box in a specific format, for which I use code similar to the one shown below:

string text=""; 
for (int i=0; i<n; i++)
{
   a=..
   b=..
   c=..
   text += String.Format("{0, -8} {1,-4} {2,8}", a, b, c);
}
MessageBox.Show(text);

So, for the following set of values:

XYZ,ABC,100

X,ABC,100

I get the following output:

XYZ     ABC     100

X     ABC     100

So you can see that the second line is poorly formatted. This is probably because I type this in a MessageBox. Space - a symbol and "space" - are different. Any solution for this?

+3
source share
5 answers

Try using \ttabs to insert between values.

+5
source

, MessageBox , M l. , . , , , , . , .

, :

text += String.Format("{0}\t{1}\t{2}", a, b, c);

, . ListView View = Details.

+2

, , , monospaced " Courier New". , .

Nevermind: MessageBox, . , MessageBox.

+1

, Windows, :

    public void Test1()
    {
        List<List<String>> list = new List<List<string>>() { 
            new List<String>() { "XYZ", "ABC","100" },
            new List<String>() { "X", "ABC", "100"},
        };

        string text = "", a = "", b = "", c = "";
        for (int i = 0; i < list.Count; i++)
        {
            a = list[i][0];
            b = list[i][1];
            c = list[i][2];
            text += String.Format("{0, -8} {1,-4} {2,8}{3}", a, b, c, Environment.NewLine);
        }
        MessageBox.Show(text);
    }

, , :

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Console.ReadKey();
        }

        public static void Test1()
        {
            List<List<String>> list = new List<List<string>>() { 
                new List<String>() { "XYZ", "ABC","100" },
                new List<String>() { "X", "ABC", "100"},
            };

            string text = "", a = "", b = "", c = "";
            for (int i = 0; i < list.Count; i++)
            {
                a = list[i][0];
                b = list[i][1];
                c = list[i][2];
                text += String.Format("{0, -8} {1,-4} {2,8}{3}", a, b, c, Environment.NewLine);
            }
            Console.WriteLine(text);
        }
    }
}

, .

, , , , MessageBox, . , , , , .

0

MessageBox, WPF, win32, () , , .

However, you can create your own MessageBox clone using the form and label (and any buttons you need), and then display it using the ShowDialog () method.

0
source

Source: https://habr.com/ru/post/1752877/


All Articles