C# Этикетка ничего не печатает - PullRequest
0 голосов
/ 17 февраля 2020

В настоящее время пытаюсь создать несколько меток динамически с помощью c# & winforms. В основном хочу добавить номер детали и, если он существует, номер партии к новой этикетке.

Я написал этот код, который работает, как ожидалось:

string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
string final_form = "";

foreach (string item in item_list)
{
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists 
    final_form = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        final_form = final_form + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    Console.WriteLine(final_form);
} 

Выходы, как и ожидалось:

PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz

Итак, я взял эту логику c в мир этикеток

string[] item_list = { "PN=12345678", "PN=1234-5678-0001", "PN=1234-4321-0001;LOT=xyz" };
string PN_EQ = "";
string LOT_EQ = "";
List<Label> labels = new List<Label>();
foreach (string item in item_list)
{
    Label lbl = new Label(); // create new label for each thing
    LOT_EQ = ""; // Clear BK_EQ after every iteration
    string[] split = item.Split(';');
    PN_EQ = split[0].Substring(3, split[0].Length - 3); // Removing PN=, will always exists 
    lbl.Name = PN_EQ // Unique Names for each label
    lbl.Text = string.Format("PN_EQ:{0}", PN_EQ);
    if(split.Length == 2)
    {
        LOT_EQ = split[1].Substring(4, split[1].Length - 4); // Removing LOT= if it exists
        lbl.Text = lbl.Text + string.Format(" LOT_EQ: {0}", LOT_EQ);
    }
    labels.Add(lbl);
    this.Controls.Add(lbl);
}

Затем выдает сообщение:

PN_EQ: 12345678
PN_EQ: // Should be output
PN_EQ: // Should be output

Но это не так! Хотите знать, если кто-нибудь знает, почему

1 Ответ

4 голосов
/ 17 февраля 2020

Давайте метод извлечения :

private static string FormatMe(string value) {
  if (string.IsNullOrEmpty(value))
    return value;
  else if (!value.StartsWith("PN="))
    return value;

  int lot = value.IndexOf(";LOT=", 3);

  if (lot >= 0)
    return $"PN_EQ: {value.Substring(3, lot - 3)} LOT_EQ: {value.Substring(lot + 5)}";
  else
    return $"PN_EQ: {value.Substring(3)}";
}

Давайте посмотрим:

  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz" 
  };

  string report = string.Join(Environment.NewLine, item_list
    .Select(item => FormatMe(item)));

  Console.Write(report);

Результат:

PN_EQ: 12345678
PN_EQ: 1234-5678-0001
PN_EQ: 1234-4321-0001 LOT_EQ: xyz

Время создания Label с (при условии WinForms):

 using System.Linq;

  ...

  string[] item_list = {
    "PN=12345678",
    "PN=1234-5678-0001",
    "PN=1234-4321-0001;LOT=xyz" 
  };

  // let's query item_list:
  //   for each item within item_list 
  //   we create a Label
  //   all the labels we materialize in a List 
  List<Label> labels = item_list
    .Select((item, index) => new Label() {
      Text     = FormatMe(item),
      Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
      AutoSize = true,
      Parent   = this, // Instead of this.Controls.Add(...);
     })
    .ToList();

Редактировать: Альтернативный номер Linq , но l oop решение:

    List<Label> labels = new List<Label>(item_list.Length); 

    for (int index = 0; index < item_list.Length; ++index)
      labels.Add(new Label() {
        Text     = FormatMe(item_list[index]),
        Location = new Point(10, 50 + 40 * index), //TODO: put the right locations here
        AutoSize = true,
        Parent   = this, // Instead of this.Controls.Add(...);
     });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...