C# 如何将另一个类中的变量放入Form1类列表框?
如何从另一个类将变量放入C# 如何将另一个类中的变量放入Form1类列表框?,c#,winforms,C#,Winforms,如何从另一个类将变量放入Form1class列表框 我在Form2窗口中将变量声明为第三类,该类按属性命名为Product。 在此之后,第二个窗口应关闭并将这些变量发送到MainWindow(Form1)列表框。 我试图让指令将变量从Form2窗口放入main窗口,但我得到了一个NullException错误。现在代码如下所示: 类别表格1: public partial class Form1 : Form { Form2 fileAdd; Product product;
Form1
class列表框
我在Form2
窗口中将变量声明为第三类,该类按属性命名为Product
。
在此之后,第二个窗口应关闭并将这些变量发送到MainWindow
(Form1)列表框。
我试图让指令将变量从Form2窗口放入main窗口
,但我得到了一个NullException
错误。现在代码如下所示:
类别表格1
:
public partial class Form1 : Form
{
Form2 fileAdd;
Product product;
public Form1()
{
InitializeComponent();
fileAdd = new Form2();
product = new Product();
}
public void actualizationButton_Click(object sender, EventArgs e)
{
if (product.Name == statusList.Text) // if product is in the listBox
{
// the instruction that will be performed if the given product is on the listBox
for (int i = product.Quantity; i < int.Parse(quantityTextBox.Text); i++)
{
product.Quantity++;
}
}
else
{
fileAdd.Show(); // launches the window to adding a new item
if (product.Name.Length != 0 && product.Code.Length != 0 &&
product.Reference.Length != 0 && product.Manufacturer.Length != 0)
{
statusList.Items.Add(product.Name + "\t" + product.Reference + "\t" +
product.Manufacturer + "\t" + product.Quantity);
product.Name = "";
product.Code = "";
product.Reference = "";
product.Manufacturer = "";
product.Quantity = 0;
// how to execute the instruction to transfer variables
//to listBox Form1 after closing Form2 window?
}
else
{
MessageBox.Show("Not included item!");
}
}
}
}
类别产品
:
class Product
{
public string Name { get; set; } = "N/A";
public string Code { get; set; } = "N/A";
public string Reference { get; set; } = "N/A";
public string Manufacturer { get; set; } = "N/A";
public int Quantity { get; set; } = 0;
}
将数据从一个表单推送到另一个表单应该是一件基本的事情,有几种方法可以做到这一点。首先:实现一个合适的构造函数,它接受
产品
对象。第二种选择是创建一个公共属性,该属性可以在创建表单后填充数据。第三,可以有一个静态字段,holind Gyor数据。每个选项都取决于您和您的设计。TinoZ建议很好,但鉴于您是初学者,我将添加一些代码来说明这些概念。显然,您的问题是Form1和Form2有完全不同的产品实例。无论你对表格2中的产品做什么,对表格1都没有影响 您的主窗体创建了一个Form2实例-在这里,您可以获取产品的新实例,并将其作为依赖项传递给“Form2”,如下所示:
Form2 fileAdd;
Product product;
public Form1()
{
InitializeComponent();
product = new Product();
fileAdd = new Form2(product);
}
然后,Form2构造函数需要理解此参数并将其分配到其字段:
Product product;
public Form2(Product product) //this is the product from main form
{
InitializeComponent();
this.product = product; //here you are making Form2 work on the same product that Form1 has.
}
最后,请整理您的代码,删除“杂音”,如果您遇到任何错误(如空引用),也请发布这些错误。您的问题包含太多不相关的信息。试着把它分解成一个简单的句子。
Product product;
public Form2(Product product) //this is the product from main form
{
InitializeComponent();
this.product = product; //here you are making Form2 work on the same product that Form1 has.
}