简体   繁体   English

如何访问另一个表单的表单控件?

[英]How to access a form control for another form?

I have two Form classes, one of which has a ListBox .我有两个Form类,其中一个有ListBox I need a setter for the SelectedIndex property of the ListBox , which I want to call from the second Form .我需要一个用于ListBoxSelectedIndex属性的设置器,我想从第二个Form调用它。

At the moment I am doing the following:目前我正在做以下事情:

Form 1表格 1

public int MyListBoxSelectedIndex
{
     set { lsbMyList.SelectedIndex = value; }
}

Form 2表格 2

private ControlForm mainForm; // form 1

public AddNewObjForm()
{
     InitializeComponent();
     mainForm = new ControlForm();           
}

public void SomeMethod()
{
     mainForm.MyListBoxSelectedIndex = -1;
}

Is this the best way to do this?这是最好的方法吗?

Making them Singleton is not a completely bad idea, but personally I would not prefer to do it that way.让它们成为 Singleton 并不是一个完全坏的主意,但我个人不喜欢那样做。 I'd rather pass the reference of one to another form.我宁愿将一个引用传递给另一种形式。 Here's an example.这是一个例子。

Form1 triggers Form2 to open. Form1 触发 Form2 打开。 Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. Form2 具有重载构造函数,它将调用 form 作为参数并提供对 Form2 成员的引用。 This solves the communication problem.这解决了通信问题。 For example I've exposed Label Property as public in Form1 which is modified in Form2.例如,我在 Form1 中将 Label 属性公开为 public,在 Form2 中进行了修改。

With this approach you can do communication in different ways.通过这种方法,您可以以不同的方式进行交流。

Download Link for Sample Project 下载示例项目的链接

// Your Form1 //你的 Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

    public string LabelText
    {
        get { return Lbl.Text; }
        set { Lbl.Text = value; }
    }
}

// Your Form2 //你的 Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private Form1 mainForm = null;
    public Form2(Form callingForm)
    {
        mainForm = callingForm as Form1; 
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.mainForm.LabelText = txtMessage.Text;
    }
}

替代文字
(source: ruchitsurati.net ) (来源: ruchitsurati.net

替代文字
(source: ruchitsurati.net ) (来源: ruchitsurati.net

Access the form's controls like this:像这样访问表单的控件:

formname.controls[Index]

You can cast as appropriate control type, Example:您可以转换为适当的控件类型,例如:

DataGridView dgv = (DataGridView) formname.Controls[Index];

It's easy, first you can access the other form like this: (let's say your other form is Form2 )这很简单,首先您可以像这样访问另一个表单:(假设您的另一个表单是Form2

//in Form 1
Form2 F2 = new Form2();
foreach (Control c in F2.Controls)
         if(c.Name == "TextBox1")
            c.Text = "hello from Form1";

That's it, you just write in TextBox1 in Form2 from Form1 .就是这样,您只需在Form1 Form2中的TextBox1中写入即可。

I usually use the Singleton Design Pattern for something like this http://en.wikipedia.org/wiki/Singleton_pattern .我通常将单例设计模式用于类似http://en.wikipedia.org/wiki/Singleton_pattern 的事情。 I'll make the main form that the application is running under the singleton, and then create accessors to forms and controls I want to touch in other areas.我将在单例下创建应用程序运行的主窗体,然后创建我想在其他区域触摸的窗体和控件的访问器。 The other forms can then either get a pointer to the control they want to modify, or the data in the main part of the application they wish to change.其他窗体然后可以获取指向他们想要修改的控件的指针,或者他们想要更改的应用程序主要部分中的数据。

Another approach is to setup events on the different forms for communicating, and use the main form as a hub of sorts to pass the event messages from one form to another within the application.另一种方法是在不同的表单上设置事件以进行通信,并使用主表单作为各种枢纽,将事件消息从应用程序中的一个表单传递到另一个表单。

If ChildForm wants to access the ParentForm如果ChildForm想要访问ParentForm

Pass ParentForm instance to the ChildForm constructor.ParentForm实例传递给ChildForm构造函数。

public partial class ParentForm: Form
{
    public ParentForm()
    {
        InitializeComponent();
    }

    public string ParentProperty{get;set;}

    private void CreateChild()
    {
         var childForm = new ChildForm(this);
         childForm.Show();
    }
}

public partial class ChildForm : Form
{
    private ParentForm parentForm;

    public ChildForm(ParentForm parent)
    {
        InitializeComponent();

        parentForm = parent;
        parentForm.ParentProperty = "Value from Child";
    }   
}

There is one more way, in case you don't want to loop through "ALL" controls like Joe Dabones suggested.还有一种方法,以防您不想像 Joe Dabones 建议的那样遍历“所有”控件。 Make a function in Form2 and call it from Form1.在 Form2 中创建一个函数并从 Form1 调用它。

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void SetIndex(int value)
    {
        lsbMyList.SelectedIndex = value;
    }
}

public partial class Form1 : Form
{
    public Form2 frm;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        frm=new Form2();
        frm.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm.SetIndex(Int.Parse(textBox1.Text));
    }
}

Here's also another example that does "Find and Highlight".这也是另一个执行“查找和突出显示”的示例。 There's a second form (a modal) that opens and contains a textbox to enter some text and then our program finds and highlights the searched text in the RichTextBox (in the calling form).还有第二个表单(模式),它打开并包含一个文本框以输入一些文本,然后我们的程序在 RichTextBox(在调用表单中)中查找并突出显示搜索到的文本。 In order to select the RichTextBox element in the calling form, we can use the .Controls.OfType<T>() method:为了在调用表单中选择 RichTextBox 元素,我们可以使用.Controls.OfType<T>()方法:

private void findHltBtn_Click(object sender, EventArgs e)
{
    var StrBox = _callingForm.Controls.OfType<RichTextBox>().First(ctrl => ctrl.Name == "richTextBox1");
    StrBox.SelectionBackColor = Color.White;

    var SearchStr = findTxtBox.Text;
    int SearchStrLoc = StrBox.Find(SearchStr);

    StrBox.Select(SearchStrLoc, SearchStr.Length);
    StrBox.SelectionBackColor = Color.Yellow;
}

Also in the same class (modal's form), to access the calling form use the technique mentioned in the @CuiousGeek's answer:同样在同一个类(模态表单)中,要访问调用表单,请使用@CuiousGeek 的答案中提到的技术:

public partial class FindHltModalForm : Form
{
        private Form2 _callingForm = null;
        public FindHltModalForm()
    {
        InitializeComponent();
    }
    public FindHltModalForm(Form2 CallingForm)
    {
        _callingForm = CallingForm;
        InitializeComponent();
    }
//...

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

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