如何将对象及其所有值从表单A传递到表单B?
下面是我制作的一些“假设代码”,我通过列表搜索以便多态地预订法案。找到名称后,我会根据预订的小时数计算价格。所有这一切都是使用对象's'完成的。所有这些代码都在表格A上的按钮上。
private void btnEnter_Click(object sender, EventArgs e)
{
string searchName = Convert.ToString(lstActs.SelectedItem);
foreach (Singer s in singers)
{
if (String.Compare(searchName, s.Name) == 0)
{
s.HoursBooked = Convert.ToInt32(nudHours.Value);
MessageBox.Show(Convert.ToString(s.HoursBooked), s.Name);
double price = s.CalculatePrice(s.Price, s.HoursBooked);
MessageBox.Show(Convert.ToString(price));
}
}
Confirm myNewForm = new Confirm();
myNewForm.ShowDialog();
this.Hide();
}
答案 0 :(得分:3)
使用您要显示的数据创建一个新类:
dnx ef dbcontext scaffold "Server=myserver;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true" EntityFramework.MicrosoftSqlServer --context ReportingDbContext --output-dir Models
填写对象:
public class ConfirmationData
{
// some properties
}
最后将数据传递给确认对话框并显示:
ConfirmationData data = new ConfirmationData();
string searchName = Convert.ToString(lstActs.SelectedItem);
foreach (Singer s in singers)
{
if (String.Compare(searchName, s.Name) == 0)
{
s.HoursBooked = Convert.ToInt32(nudHours.Value);
MessageBox.Show(Convert.ToString(s.HoursBooked), s.Name);
double price = s.CalculatePrice(s.Price, s.HoursBooked);
MessageBox.Show(Convert.ToString(price));
.... fill 'data' with the Information you want to display
}
}
答案 1 :(得分:0)
你的确认课程的工作取决于辛格课程的价值,不是吗?如果是这样,您可以向Confirm构造函数添加一个参数,如下所示:
public Confirm(Singer singer)
{
//null-check I suppose
}
所以你写的按钮处理程序会这样结束:
Confirm myNewForm = new Confirm(s);//where s is Singer
myNewForm.ShowDialog();
this.Hide();
否则,您可以向Confirm类添加新的公共属性,并在显示对话框之前为其指定值:
Confirm myNewForm = new Confirm();
myNewForm.Singer = s;
myNewForm.ShowDialog();
this.Hide();