winform 中标签或文本框的 C# 计数

C# count of labels or textboxs in win form

如何动态检索winform中的标签数量?因为在我的表单中我有大约 12 个标签,如果我按下按钮我想将每个标签更改为文本框。因此,总而言之,我想让每个标签都可编辑,并在编辑并保存后将其更改回标签。总之,它就像可编辑的标签。 但是为每个标签编写更改需要花费大量时间和代码行,因此如果可以使其动态化我将是完美的。谢谢。

我建议使用 TextBoxes,而不是 Labels 来包含任何可以编辑的文本。 所以我们在 2 中有 TextBox 不同的模式 Label Mode(无编辑)和 TextBox Mode. 在它们之间切换(假设 WinForms):

// Make TextBox to look like a label: readonly, color, border etc.
private static void ToLabelMode(TextBox box) {
  if (null == box)
    return;

  box.HideSelection = true;
  box.BackColor = SystemColors.Control;
  box.ReadOnly = true;
  box.BorderStyle = BorderStyle.None;
}

private static void ToTextBoxMode(TextBox box) {
  if (null == box)
    return;

  box.HideSelection = false;
  box.BackColor = SystemColors.Window;
  box.ReadOnly = false;
  box.BorderStyle = BorderStyle.Fixed3D;
}

那么你就可以使用它们了:

TextBox[] m_TextBoxes;

private void MyForm_Load(object sender, EventArgs e) {
  m_TextBoxes = new TextBox[] {
    textBoxFirstName, 
    textBoxLastName, 
    //TODO: Put the relevant ones
  };

  // Let all TextBox be in Label mode
  EnableEdit(false);
}

private void EnableEdit(bool enabled) {
  foreach (var box in m_TextBoxes)
    if (enabled)
      ToTextBoxMode(box);
    else 
      ToLabelMode(box); 
}

编辑: 如果您坚持 LabelTextBox 我建议两者都用使用 Visible 显示正确的控件(Label 或相应的 TextBox):

Dictionary<Label, TextBox> m_TextBoxesPairs;

private void MyForm_Load(object sender, EventArgs e) {
  m_TextBoxesPairs = new Label[] {
    labelFirstName,
    labelSecondName,
    //TODO: put all the relevant labels here
  }
  .ToDictionary(lbl => lbl,
                lbl => new TextBox() {
                  Parent   = lbl.Parent,
                  Text     = lbl.Text,
                  Location = lbl.Location,
                  Size     = lbl.Size,
                  Visible  = false
                });

  // If you want to modify Label.Text on TextBox.Text changing
  foreach (var pair in m_TextBoxesPairs)
    pair.Value.TextChanged += (o, ee) => {pair.Key.Text = pair.Value.Text;} 

  EnableEdit(false);  
}

private void EnableEdit(bool enabled) {
  foreach (var pair in m_TextBoxesPairs) {
      pair.Key.Visible = !enabled;
      pair.Key.Visible =  enabled;
    } 
}

尝试以下操作:

            Control[] labels = this.Controls.Cast<Control>().Where(x => x.GetType() == typeof(Label)).ToArray() ;
            for(int i = labels.Length - 1; i >= 0; i--)
            {
                Label label = (Label)labels[i];
                TextBox newBox = new TextBox();
                newBox.Left = label.Left;
                newBox.Top = label.Top;
                newBox.Width = label.Width;
                newBox.Height = label.Height + 10;
                newBox.Text = label.Text;
                label.Parent.Controls.Add(newBox);
                label.Parent.Controls.Remove(label);
            }