简体   繁体   English

Windows 窗体中的 C# 列表框填充

[英]C# list boxes padding in windows forms

I am making a small point of sale app.我正在制作一个小型销售点应用程序。 I want to add space between product name and price.我想在产品名称和价格之间添加空格。 I uses Pad Right(45) after product name.我在产品名称后使用Pad Right(45) Problem is that if product name is bigger then prices not align in same line.问题是,如果产品名称较大,则价格不会在同一行中对齐。 please help me.请帮我。

在此处输入图片说明

You could write method along these lines,你可以按照这些方式编写方法,

    public class Data
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }
    //Takes data list and desired lenght of merged string data
    public static List<string> MergeData(List<Data> data, int maxLenght)
    {
        List<string> mergedData = new List<string>();
        foreach (var d in data)
        {
            //Calculates how many spaces are needed to be inserted between Name and Price
            int numberOfSpacesNeeded = maxLenght - (d.Name.Length + d.Price.ToString().Length);
            //Builds new string with merged data
            var sb = new StringBuilder();
            sb.Append(d.Name)
                .Append(' ', numberOfSpacesNeeded)
                .Append(d.Price.ToString());
            mergedData.Add(sb.ToString());
        }
        return mergedData;
    }

Second solution that doesn't require maxLength parameter不需要 maxLength 参数的第二种解决方案

    public static List<string> MergeData(List<Data> data)
    {
        int maxLenght = data.Max(x => x.Name.Length + x.Price.ToString().Length) + 1;
        List<string> mergedData = new List<string>();
        foreach (var d in data)
        {
            string name = d.Name;
            int numberOfSpacesNeeded = maxLenght - (d.Name.Length + d.Price.ToString().Length);
            var sb = new StringBuilder();
            sb.Append(name)
                .Append(' ', numberOfSpacesNeeded)
                .Append(d.Price.ToString());
            mergedData.Add(sb.ToString());
        }
        return mergedData;
    }

Both of these solutions will align Price to the right , if you want to align it to left you should find max length of the price and RightPad other prices to match its length before calculating how many spaces should you add between Name and Price.这两种解决方案都会将 Price 向右对齐,如果您想将其向左对齐,则在计算应在 Name 和 Price 之间添加多少空格之前,您应该找到价格的最大长度和 RightPad 其他价格以匹配其长度。

Can you shorten the product name?你能缩短产品名称吗?

        string str = "12345678901234567890";
        str = str.Remove(15);
        str = str.PadRight(45);
        Console.WriteLine(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM