Skip to main content
 首页 » 编程设计

c#之如何在 c# 中从另一个 winform 运行一个方法

2024年02月23日16qq号

我在名为 Products 的表单中有一个“addEngine”方法,我有一个“添加新引擎”按钮。

public partial class Products : Form 
{  
    public void addEngine(short EngineID, string NumberPerUnit, string Manufacturer, string ModelSeriesYear) 
    { 
        try   
        { 
            productCurrentRow = ((DataRowView) productEngineBindingSource.Current).Row; 
            int productID = (int) productCurrentRow["ProductID"]; 
 
            var engines = from engine in productDataset.ProductEngine 
                          where engine.ProductID == productID 
                          select engine; 
 
            foreach (var engine in engines) 
            { 
                if (engine.EngineID == EngineID) 
                { 
                    UC.alertError("Record already exists!"); 
                    return; 
                } 
            } 
 
            var newEngineRow = productDataset.ProductEngine.NewProductEngineRow(); 
            newEngineRow.EngineID = EngineID; 
            newEngineRow.ProductID = productID; 
            newEngineRow.NumberPerUnit = NumberPerUnit; 
            newEngineRow.Manufacturer = Manufacturer; 
            newEngineRow.ModelSeriesYear = ModelSeriesYear; 
 
            productDataset.ProductEngine.AddProductEngineRow(newEngineRow); 
        } 
        catch (Exception ex) 
        { 
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        } 
    } 
 
    private void btnAddNewEngine_Clicked(object sender, EventArgs e) 
    { 
        EngineFilter eginfilter = new EngineFilter(); 
        eginfilter.ShowDialog(); 
    } 
} 

单击该按钮时,会出现另一个名为“EngineFilter”的表单,它会加载引擎列表。用户从列表中选择一个项目并单击表单上的“选择”按钮后,该项目的信息将通过“产品”表单上的“addEngine”方法插入一个列表(ProductEngine 数据表)。问题是我不能在两种形式(类)之间传递参数

public partial class EngineFilter : Form 
{ 
    public delegate void addEnineDelegate(short EngineID, string NumberPerUnit, string Manufacturer, string ModelSeriesYear); 
 
    private void btnSelect_Click(object sender, EventArgs e) 
    { 
        Products product = new Products();                 
        DataRow row = ((DataRowView) engineFilterBindingSource.Current).Row; 
        addEnineDelegate mydelegate = new addEnineDelegate(product.addEngineMethod); 
 
        mydelegate((short)row[2], "1", row[0].ToString(), row[1].ToString()); 
        this.Close(); 
    } 
} 

我已尝试使用委托(delegate),但出现“未将对象引用设置到对象实例”的错误。有没有人可以给我一个好的做法来处理这个问题?

请您参考如下方法:

您可以将对包含 addEngine 方法的表单的引用传递给要从中调用此方法的表单,这会起作用,但这不是一个特别好的解决方案。

更好的办法是有一个公开此方法的类,然后将此类的实例传递给两个表单以供它们使用。这有更好的关注点分离。实际上,您的表单不应该负责更新存储库,它应该做的是收集用户输入并将其传递给负责进行更新的类。