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

编程入门 行业动态 更新时间:2024-10-11 03:20:25
本文介绍了如何访问另一个表单的表单控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个 Form 类,其中一个有一个 ListBox.我需要为 ListBox 的 SelectedIndex 属性设置一个 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)

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)

(source: ruchitsurati)

更多推荐

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

本文发布于:2023-11-02 09:58:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552075.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   控件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!