[Form] Value transfer between two Winform forms through delegated events, basics

2023, Week 38. Give yourself a goal, and then stick to it and you will always get something. If you don’t believe me, try it!
In actual projects, we may use some forms to make some small tools or functions. For example: run the program, click a button on the main form A, and hope that form B will pop up.
After form B completes the operation, you hope to transfer the value back to form A, and then perform other business operations.

Insert image description here

1. Display online pictures

To dynamically assign a picture link to a PictureBox control in C# WinForm, you can use Image.FromUrlthe method to load a remote picture and assign it to Imagea property of the PictureBox.

  • Here is a simple example code:

First, add a PictureBox control to your WinForm form.

Then, in the form's code file, add the following reference:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net;

Next, in the event where you want to assign the image link (such as a button click event), add the following code:

private void button1_Click(object sender, EventArgs e)
{
    
    
    try
    {
    
    
        // 获取图片链接
        string imageUrl = "https://example.com/image.jpg"; // 替换为你的图片链接

        // 使用WebClient下载图片
        WebClient client = new WebClient();
        byte[] imageData = client.DownloadData(imageUrl);
        MemoryStream ms = new MemoryStream(imageData);

        // 创建并分配图片给PictureBox
        Image image = Image.FromStream(ms);
        pictureBox1.Image = image;
    }
    catch (Exception ex)
    {
    
    
        // 处理异常
        MessageBox.Show("加载图片时出错:" + ex.Message);
    }
}

In the above example, we used WebClientto download the image data and convert it into Imagean object.
We then assign the image to the PictureBox's Imageproperty so that the picture can be displayed on the form.

Note that in order to run the example properly, make sure your application can access the specified image link.

2. Display local pictures

To load a local picture into a PictureBox control in C# WinForm, you can use Image.FromFilethe method to load a local picture file and assign it to Imagea property of the PictureBox.

  • Here is a simple example code:

First, add a PictureBox control to your WinForm form.

Then, in the form's code file, add the following reference:

using System;
using System.Drawing;
using System.Windows.Forms;

Next, in the event where you want to load a local image (such as a button click event), add the following code:

private void button1_Click(object sender, EventArgs e)
{
    
    
    try
    {
    
    
        // 获取本地图片文件路径
        string imagePath = "C:\\path\\to\\your\\image.jpg"; // 替换为你的图片文件路径

        // 加载本地图片文件
        Image image = Image.FromFile(imagePath);

        // 将图片分配给PictureBox
        pictureBox1.Image = image;
    }
    catch (Exception ex)
    {
    
    
        // 处理异常
        MessageBox.Show("加载图片时出错:" + ex.Message);
    }
}

In the above example, we use Image.FromFilethe method to load the image file at the specified path and convert it into Imagean object.
We then assign the image to the PictureBox's Imageproperty to display the picture on the form.

Please note, replace the example code with imagePathyour actual local image file path.

3. Form A opens form B

To open another form in C# WinForm, you can use Forman instance of the class to create a new form and call its Showor ShowDialogmethods to display it.

  • Here is a simple example code:

Suppose you have created two forms: Form1and Form2.

In Form1a form, you can add a button that opens the form on the button's click event Form2. code show as below:

private void button1_Click(object sender, EventArgs e)
{
    
    
    // 创建Form2窗体实例
    Form2 form2 = new Form2();

    // 显示Form2窗体
    form2.Show();
}

If you want to open another form modally, that is, Form2display it completely before continuing Form1, you can use ShowDialogthe method.

  • The sample code is as follows:
private void button1_Click(object sender, EventArgs e)
{
    
    
    // 创建Form2窗体实例
    Form2 form2 = new Form2();

    // 以模态方式显示Form2窗体
    form2.ShowDialog();
}

In the above example, we first create an instance of the form to open and then call Showa method or ShowDialogmethod to display the form.

4. Event mechanism transfers value

To pass the value selected from form B to form A, you can do it in the following ways:

4.1. Subscription events

Define a property or field in the B form to hold the selected value. When the B form is closed, pass the selected value back to the A form.

In the code of the B form, you can define a public property or field to hold the selected value:

public string SelectedValue {
    
     get; set; }

In the event in the B form (such as the button click event), assign the selected value to SelectedValue:

private void button1_Click(object sender, EventArgs e)
{
    
    
    SelectedValue = comboBox1.SelectedItem.ToString();
    this.Close();
}

In the code of form A, create an instance of form B and subscribe to FormClosingthe events of form B to get the selected value:

private void button1_Click(object sender, EventArgs e)
{
    
    
    BForm bForm = new BForm();
    bForm.FormClosing += (s, args) =>
    {
    
    
        if (!string.IsNullOrEmpty(bForm.SelectedValue))
        {
    
    
            // 使用bForm.SelectedValue在A窗体中进行操作
            MessageBox.Show(bForm.SelectedValue);
        }
    };
    bForm.ShowDialog();
}

4.2. Event mechanism

Use delegate and event mechanisms to pass values.

In the code of the B form, first define a delegate and event:

public delegate void ValueSelectedEventHandler(string selectedValue);
public event ValueSelectedEventHandler ValueSelected;

In an event in the B form (such as a button click event), trigger the event and pass the selected value:

private void button1_Click(object sender, EventArgs e)
{
    
    
    string selectedValue = comboBox1.SelectedItem.ToString();
    ValueSelected?.Invoke(selectedValue);
    this.Close();
}

In the code of form A, create an instance of form B and subscribe to the events of form B to get the selected value:

private void button1_Click(object sender, EventArgs e)
{
    
    
    BForm bForm = new BForm();
    bForm.ValueSelected += (selectedValue) =>
    {
    
    
        // 使用selectedValue在A窗体中进行操作
        MessageBox.Show(selectedValue);
    };
    bForm.ShowDialog();
}

With one of the above methods you can get the value selected from form B in form A and manipulate it where needed.

5. Basic concepts

In C#, Delegate, Event, Message, Publish and Subscribe are several related concepts, and there are some relationships and connections between them.

  • The following briefly introduces the relationship between them:

5.1. Delegate

A delegate is a type that can reference one or more methods and allow those methods to be called through the delegate. Delegates provide a mechanism for passing methods as parameters and allow function calls to be made in the form of callbacks.

5.2. Event

Events are a delegation-based mechanism used to implement communication and interaction between objects. Objects can have events defined as their members and raise (fire) events under specific conditions. Other objects can subscribe to (or register for) events to receive notifications and execute appropriate handling methods when the events occur.

5.3. Message

Messages are a mechanism for exchanging data and information between objects. It is passed between different components to trigger the corresponding behavior or action. Messages can be synchronous or asynchronous and can contain parameters, events, or other data.

5.4. Publish and Subscribe

The publish-subscribe pattern is a software design pattern used to achieve decoupling and loose coupling between objects. In this pattern, one object (publisher) notifies other objects (subscribers) that an event has occurred or a message has been sent, and subscribers can selectively receive and process these events or messages.

In C#, the publish-subscribe pattern is usually implemented by defining delegates and events. The publisher publishes events and the subscribers subscribe and process the events.
Events are a special type of delegate that provide a higher level of encapsulation and security.

Through delegation and events, loosely coupled communication between objects can be achieved to achieve a more flexible, extensible and maintainable code structure.

Guess you like

Origin blog.csdn.net/lmy_520/article/details/132849699