我有这段代码可以将它从 Form1 发送到 Form2:
public partial class Form1 : Form
{
public ShoppingBasket myBasket = new ShoppingBasket();
public Form1()
{
InitializeComponent();
}
private void editButton_Click(object sender, EventArgs e)
{
int c = lstCart.Items.Count - 1;
for (int i = c; i <= 0; i++)
{
if (lstCart.GetSelected(i))
{
Form2 fm2 = new Form2();
fm2.productNameTextBox.Text = myBasket[i].ProductName;
fm2.quantityTextBox.Text = Convert.ToString(myBasket[i].Quantity);
fm2.latestPriceTextBox.Text = Convert.ToString(myBasket[i].LatestPrice);
fm2.ShowDialog();
}
}
}
}
然后这是我的 Form2 代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
Form1 fm1 = new Form1();
private void okBtn_Click(object sender, EventArgs e)
{
int c = fm1.lstCart.Items.Count - 1;
for (int i = c; i <= 0; i++)
{
if (this.fm1.lstCart.GetSelected(i))
{
this.fm1.myBasket[i].ProductName = this.productNameTextBox.Text;
this.fm1.myBasket[i].Quantity = Convert.ToInt32(this.quantityTextBox.Text);
this.fm1.myBasket[i].LatestPrice = Convert.ToDecimal(this.latestPriceTextBox.Text);
this.Close();
}
}
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
这是我的 ShoppingBasket 课程:
public class ShoppingBasket : List<OrderItem>
{
public ShoppingBasket()
{
}
public decimal BasketTotal { get; set; }
public new void Add(OrderItem i)
{
base.Add(i);
}
public new void Remove(OrderItem i)
{
base.Remove(i);
}
订单项类:
public class OrderItem
{
public OrderItem(string productName,
decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
我遇到的问题是它给了我:'ArgumentOutOfRangeException 未处理'说“索引 -1 超出范围。参数名称:索引”指向此行:if (this.fm1.lstCart.GetSelected(i))
但以前它给了我另一个错误,说“对象引用未设置为对象的实例”。
如何使之前在 Form1 中选定字段中的值更改为我从 Form2 传递回 Form1 的值?