Scene:
Windows Forms applications often require data interaction between multiple windows, such as filling controls on another window according to the choice of one window.
Question:
How to set up the selectedValue of the second window by selecting the line in the first window to set the line in the DataGridView to fill the Combobox to fill the Combobox with this value? Solution:
In Windows Forms, the windows are similar to other C#categories, and the communication methods between the windows are the same as the inter -class communication method.
Operation the second window in the first window:
Construct function parameter transfer:
Add necessary parameters to the constructor of the second window. When creating a second window instance, the value is passed to the constructor. Public attributes or methods:
Create public attributes or methods in the second window, and set these attributes after creating a second window instance. In this way, the second window can access these values.Inject it into the Action commission: Define a public attribute of the Action entrusted type in the second window. When creating a second window instance, use custom Action to assign the attribute. When you need to operate the first window, call the Action in the second window.
In the first window:
The first window operates from the second window
Example 3 -Transfer the instance of the first window to the second window and use a public method:
When creating FORM2:<code class="language-csharp">public partial class Form2 : Form { int selectedValue; public Form2(int value) { InitializeComponent(); selectedValue = value; } private void Form2_Load(object sender, EventArgs e) { // 加载数据 this.comboBox1.DataSource = new MyDbContext().Categories.ToList(); // 假设Categories是数据库表 this.comboBox1.DisplayMember = "Name"; this.comboBox1.ValueMember = "Id"; this.comboBox1.SelectedValue = selectedValue; } }</code>
These examples show the implementation of different methods, which method to choose depends on the specific application scenario and code structure. It is recommended to give priority to the use of public attributes or methods to avoid direct public control to improve the maintenance and readability of the code.
<code class="language-csharp">int value = 2; // 或从DataGridView获取 Form2 f = new Form2(value); f.ShowDialog();</code>
The above is the detailed content of How to Set a ComboBox's SelectedValue on a Second Form by Selecting a DataGridView Row on the First Form?. For more information, please follow other related articles on the PHP Chinese website!