WinForms passing data between Forms [duplicate]

你说的曾经没有我的故事 提交于 2019-11-28 02:28:56

You should try to split your UI-code and your database code. This is called Layering (MVVM, MVC, MVP,...) but you don't have to!

There are several ways:

1) Make a class that both forms can reference and execute your database logic there. (that would be the cleanest way for now)

2) Create an Event in your Form with the menu and react on it in the other Form

3) Your menu Form holds a reference to the other Form and executes a Method on it passing the selected subitem.

In code

1

public static class SqlClass
{
    public static void ExecuteQuery(string menuItem)
    {
        //execute query
    }
}


Form 1
//menu changed...
SqlClass.ExecuteQuery(menuItem)

2

Form1:
public event EventHandler<string> MenuItemChanged;

//menu changed...
if(this.MenuItemChanged != null)
    this.MenuItemChanged(this, menuitem)


Form2:
public Form2(Form1 otherForm)
{
    InitializeComponent();
    _otherForm.MenuItemChange += //... handle your sql code
}

3

private readonly Form2 _otherForm;

public Form1(Form2 otherForm)
{
    InitializeComponent();
    _otherForm = otherForm;
}

//menu changed...
otherForm.ExecuteQuery(menuitem);

For the examples, Form 2 is the form where you want to execute your query because there is the Method/Event-Handler defined that will interact with your database.

To understand the solution, you need a more high level perspective - you get an information in code behind of a Form (a Class) and you want to consume that information somewhere else.
In general you need a reference to the Form that holds the information you are interested in and it tells you the information when changed (Event) OR
the information source tells every interested destination (calls a Method). Then the Information source hold the references to the consumers.
Both concepts are the same just the direction of the communication (and reference) changes.

The alternative (Option 1) is that you move your information destination somewhere else (e.g. in a static class) and consume it there. The Mechanism of passing the information is pretty much the same (via a parameterized Method call) but it encapsulates the UI-colde (Form) from the Database code (SQL query execution)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!