简体   繁体   English

从表单C#继承

[英]Inheriting from a form c#

everybody. 大家 My plan is to create a separate class, in which I would declare all the labels and textbox values. 我的计划是创建一个单独的类,在其中声明所有标签和文本框值。 But to do so I have to inherit from a form. 但是要做到这一点,我必须继承一种形式。 The problem is that when I inherit from a form my class becomes a form and calls elements from itself. 问题是,当我从表单继承时,我的班级变成了表单,并从自身调用元素。 Setting the properties of labels and textboxes to public did not help. 将标签和文本框的属性设置为public并没有帮助。 Any ideas? 有任何想法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Assignment2v3
{
class Declarations : Form1
{
    public List<Label> ErrRep
    { get; set; }
    public List<TextBox> TextBoxes
    { get; set; }
    public List<ComboBox> ComboBoxes
    { get; set; }
    public Declarations()
    {
        ErrRep = DeclareErrorReports();
        TextBoxes = DeclareTextBoxes();
        ComboBoxes = DeclareComboBoxes();
    }
    List<Label> DeclareErrorReports()
    {
        var ER = new List<Label>();
        ER.Add(errorReport1);
        ER.Add(errorReport2);
        ER.Add(errorReport3);
        return ER;
    }//Would be used if try catch worked
    List<TextBox> DeclareTextBoxes()
    {
        List<TextBox> TextBoxes = new List<TextBox>();
        TextBoxes.Add(textBoxPizza1);
        TextBoxes.Add(textBoxPizza2);
        TextBoxes.Add(textBoxPizza3);
        return TextBoxes;
    }//Puts all textBoxes into a list
    List<ComboBox> DeclareComboBoxes()
    {
        var ComboBoxes = new List<ComboBox>();
        ComboBoxes.Add(comboBoxPizza1);
        ComboBoxes.Add(comboBoxPizza2);
        ComboBoxes.Add(comboBoxPizza3);
        return ComboBoxes;
    }//Puts all comboboxes into a list
     // ^ Boring declarations
}
}

表格设计

You should probably inherit from UserControl instead. 您可能应该继承自UserControl。 With your own UserControl, you can add it to one or more forms in one or more places. 使用自己的UserControl,可以将其添加到一个或多个位置的一个或多个表单中。

There are plenty of tutorials out there which guide you in creating your own WinForms UserControl. 有很多教程可以指导您创建自己的WinForms UserControl。

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

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