如何访问另一个表单的表单控件? [英] How to access a form control for another form?

查看:36
本文介绍了如何访问另一个表单的表单控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Form 类,其中一个有一个 ListBox.我需要为 ListBoxSelectedIndex 属性设置一个 setter,我想从第二个 Form 调用它.

目前我正在做以下事情:

表格 1

public int MyListBoxSelectedIndex{设置 { lsbMyList.SelectedIndex = 值;}}

表格 2

private ControlForm mainForm;//表格 1公共 AddNewObjForm(){初始化组件();mainForm = new ControlForm();}public void SomeMethod(){mainForm.MyListBoxSelectedIndex = -1;}

这是最好的方法吗?

解决方案

使它们成为单例并不是一个完全坏的主意,但我个人不喜欢那样做.我宁愿将一个引用传递给另一种形式.这是一个例子.

Form1 触发 Form2 打开.Form2 具有重载构造函数,它将调用 form 作为参数并提供对 Form2 成员的引用.这解决了通信问题.例如,我在 Form1 中将 Label 属性公开为 public,而在 Form2 中进行了修改.

通过这种方法,您可以以不同的方式进行交流.


(来源:
(来源:ruchitsurati.net)

I have two Form classes, one of which has a ListBox. I need a setter for the SelectedIndex property of the ListBox, which I want to call from the second Form.

At the moment I am doing the following:

Form 1

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

Form 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. I'd rather pass the reference of one to another form. Here's an example.

Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.

With this approach you can do communication in different ways.

Download Link for Sample Project

//Your 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

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)


(source: ruchitsurati.net)

这篇关于如何访问另一个表单的表单控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆