我有两种不同的形式,一种是我生成一个客户列表,另一种是我需要检索添加到列表中的信息。如何将列表传递给我的第二个表单?
这是第一个表格
List<Customers> new_customer = new List<Customers>();
private void newCustomer_Load(object sender, EventArgs e)
{
}
private void fNameTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void lNameTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void addressTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void phoneNumTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void emailTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void IDTxtBox_TextChanged(object sender, EventArgs e)
{
}
private void addNewCustButton_Click(object sender, EventArgs e)
{
if (fNameTxtBox.Text != "" && lNameTxtBox.Text != "" && addressTxtBox.Text != "" && phoneNumTxtBox.Text != "" && emailTxtBox.Text != "" && IDTxtBox.Text != "")
{
new_customer.Add(new Customers { FName = fNameTxtBox.Text, LName = lNameTxtBox.Text, Address = addressTxtBox.Text, phoneNum = phoneNumTxtBox.Text, emailAdd = emailTxtBox.Text, ID = int.Parse(IDTxtBox.Text) });
MessageBox.Show("Thanks for Registering");
}
else
{
MessageBox.Show("Customer not added! Please fill out the entire form!");
}
}
}
}
这是第二种形式:
namespace WindowsFormsApplication1
{
public partial class Current_Customers : Form
{
public Current_Customers()
{
InitializeComponent();
}
private void currCustComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:1)
像这样创建一个form2的新构造函数,同时也以第二种形式创建一个列表。
public partial class Current_Customers : Form
{
List<Customers> new_customer = new List<Customers>();
public Current_Customers(List<Customers> customers)
{
new_customer=customers;
}
}
当您在form1中创建此表单的对象时,请执行此操作
Current_Customers cus=new Current_Customers(new_customer);
这会将列表传递给第二种形式。
答案 1 :(得分:0)
您有两种可能的方法。
1)在两个表格上列出公共字段/属性。如果两个表单都存在于同一范围内,则它们可以相互引用。
2)将列表添加到两个表单都可以访问的第三个类,最好是静态类。这将是我个人的偏好。
public static class StaticData
{
public static readonly List<Customers> _Customers = new List<Customers>();
public static List<Customers> CustomerList
{
get
{
if (_Customers.Count < 1)
{
//Load Customer data
}
return _Customers;
}
}
}
public class Form1
{
private List<Customers> new_customer = null;
public Form1()
{
this.new_customer = StaticData.CustomerList;
}
}
public class Current_Customers
{
private List<Customers> new_customer = null;
public Current_Customers()
{
this.new_customer = StaticData.CustomerList;
}
}
虽然我的例子不是真正的线程安全,而是为了让你指向正确的方向。