如何从一种形式到另一种形式获得相同的价值两种不同的形式 [英] How to get same value from one form to another two difrent forms
问题描述
我有2个表格 novkontakt 和 novkontakt1 谁应该从 tipNaLice 表格获得相同的价值,
一个表单kontakt工作完美,但是当添加secound有错误时
I have 2 forms novkontakt and novkontakt1 who should get same value from tipNaLice form,
when is one form kontakt work perfect, but when add secound have error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
我的尝试:
这是我的代码来自tipNaLice
What I have tried:
this is my code from tipNaLice
novKontakt orForm;
novKontakt1 or1Form;
public tipNaLice(novKontakt inForm)
{
orForm = inForm;
InitializeComponent();
}
public tipNaLice(novKontakt1 in1Form)
{
or1Form = in1Form;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
foreach (object redovi in listBox1.SelectedItems)
{
orForm.textLice = redovi.ToString();
orForm.vmetniTipNaLice();
or1Form.textLice1 = redovi.ToString();
or1Form.vmetniTipNaLice1();
this.Close();
}
}
推荐答案
不要这样做。这意味着你的表单需要了解彼此以及它们是如何工作的 - 这很糟糕,并且使你的代码难以正确维护。
具体取决于关系 两种形式之间。
看看这些,其中一个适合你的情况。
创建另一个实例的表格:
Don't do it that way. That means that your forms need to know about each other and how they work - that's bad and makes your code hard to maintain properly.
Exactly how depends on the "relationship" between the two forms.
Have a look at these, one of them will fit your circumstances.
The form that creates an instance of another:
MyForm mf = new MyForm();
mf.Show();
是父,另一种形式是孩子。
(这并不意味着任何正式的MDI关系)
转让两种表格之间的信息,第1部分:父母与子女 [ ^ ]
在两种表格之间传递信息,第2部分:儿童到父母 [ ^ ]
在两种形式之间传递信息,第3部分:儿童到儿童 [ ^ ]
Is the "parent", the other form is the "child".
(This doesn't imply any formal MDI relationship)
Transferring information between two forms, Part 1: Parent to Child[^]
Transferring information between two forms, Part 2: Child to Parent[^]
Transferring information between two forms, Part 3: Child to Child[^]
当 novKontakt1时表单是开放做某事(在我的情况下从列表框发送值)
所以这是我的解决方案
When novKontakt1 form is open do something (in my case send value from listbox)
so this is my solution
public static Form OpenForm(Type FormType)
{
foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.GetType() == FormType)
return OpenForm;
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
novKontakt1 nk1 = null;
foreach (object redovi in listBox1.SelectedItems)
{
if ((nk1 = (novKontakt1)OpenForm(typeof(novKontakt1))) == null)
{
orForm.textLice = redovi.ToString();
orForm.vmetniTipNaLice();
}
else
{
or1Form.textLice1 = redovi.ToString();
or1Form.vmetniTipNaLice1();
}
this.Close();
}
}
这篇关于如何从一种形式到另一种形式获得相同的价值两种不同的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!