在WinForms c#中动态编辑两个表单之间的数据 [英] Dynamically edit the data between two forms in WinForms c#

查看:27
本文介绍了在WinForms c#中动态编辑两个表单之间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式.主表单是用户通过按钮选择项目并将它们添加到表单中的列表视图的地方.然后有一个结账"按钮,打开第二个表单,用户可以在其中编辑创建的订单.我使用序列化来保存数据,所以当回到以前的表单时,列表的当前状态会显示出来.但是当我尝试添加新项目时,以前的项目会被替换.如何在不丢失任何数据的情况下在两个表单之间进行动态通信?

I have two forms. The main form is where the user select items, through buttons and they are added to a listview in the form. Then there is a button "Check out" which opens the second form, where the user can edit the created order. I used serialization to save the data so when get back to the previous form, the current state of the list shows up. But when I try to add new items, the previous are replaced. How to make a dynamic communication between the two forms without loosing any data?

这是我的第一种形式:

private void buttonCheckOut_Click(object sender, EventArgs e)
        {
            var binFormatter = new BinaryFormatter();
            using (var fileStream = new FileStream(@"D:\productsList.txt", 
                FileMode.Create, FileAccess.Write))
                binFormatter.Serialize(fileStream, productsList);
CheckOutForm checkOut = new CheckOutForm(TotalBill.Text, productsList, false);
            this.Hide();
            checkOut.ShowDialog();
}

第二种形式的反序列化如下所示:

And the deserialzation in the second form looks like this:

        Form1 f = new Form1(null);


        var binFormatter = new BinaryFormatter();
        using (var fileStream = new FileStream(@"D:\productsList.txt",
           FileMode.Open, FileAccess.Read))
        {
            productsList1 = (List<Product>)binFormatter.Deserialize(fileStream);
            foreach (var pr in productsList1)
            {
                    f.listView1.Items.Add(pr.ToString());
            }
        }

推荐答案

您正在做的事情过于复杂.让您的两个表单都引用一个 ProductsListService 类,该类管理产品列表(通过适当的方法).

What you're doing is overcomplicated. Have both of your forms reference a ProductsListService class which manages the products list (through appropriate methods).

public class ProductsListService
{
  List<Product> GetProducts();
  void AddProduct(Product product);
  ...
}

您的主表单类可以自己创建此服务,也可以通过任何创建它的人将其传递给它.然后你可以把这个服务传递给你的第二个表单:

Your Main form class can create this service itself or it can be passed into it by whatever creates it. Then you can pass this service to your second form:

CheckOutForm checkOut = new CheckOutForm(TotalBill.Text, productsListService, false);
            this.Hide();

checkoutForm 将只使用此服务,不需要将任何内容传递回主表单,因为它们都使用相同的对象.

The checkoutForm will just use this service and doesn't need to pass anything back to the main form since they're both using the same object.

这篇关于在WinForms c#中动态编辑两个表单之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆