简体   繁体   中英

How can I run a method from a another winform in c#?

I have an "addEngine" method in a form called Products and i have an "Add New Engine" button.

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();
    }
}

When the buttion is clicked there is another form called "EngineFilter", which loads a list Engines. After user selects an item from the list and clicks "Select" buttion on the form, the information of the item is inserted a list (ProductEngine datatable) through the "addEngine" method on the "Product" form. The problem is that i cannot pass the parameters between the two forms(classes)

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();
    }
}

I've tried to use a delegate but there is a "Object reference not set to an instance of an object" error. Is there anybody can give me a good practice to handle this?

I aggree with Sam Holder, but if you want this code to work as it is right now, I would use events.

Create your event in the EngineFilter

Public event EventHandler<EngineFilterEventArgs> EngineFilterSelected;

Now second step is to create the EngineFilterEventArgs class and put every parameter you want in the eventargs. Now I have just added an ID

Public class EngineFilterEventArgs : EventArgs
{
    Public int Id {get; set;}
    Public EngineFilterEventArgs(int id)
    {
        Id = id;
    }
}

Third step is to fire the event. Note that 1 is selectedId

If(EngineFilterSelected != null)
     EngineFilterSelected(this, new EngineFilterEventArgs(1));

Now make sure that the other form is listening to the event.

    private void btnAddNewEngine_Clicked(object sender, EventArgs e)
    {
        EngineFilter enginFilter = new EngineFilter();
        engineFilter.EngineFilterSelected += handler;
        engineFilter.ShowDialog();
    }

Final step is to add your eventhandler

Protected void handler(object sender, EngineFilterEventArgs e)
{
    //TODO Handle your event
    Int selectedId = e.Id;
}

You could pass a reference to the form which contains the addEngine method to the form which you want to call this method from, and that would work, but is not a particularly great solution.

Better would be to have a class which exposes this method, then pass the instance of this class to both forms for them to use. This has better separation of concerns. Really your form should not be responsible for updating the repository, what it should do is collect the user input and pass it to the class responsible for doing the update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM