I want to fill a combobox on Form1 , when the OK button on Form2 is clicked.
First, the Load Form2 button on Form1 is clicked to display Form2. Then, Form2 appears, and
Your design sounds like Form2 is used as a Dialog. While your design approach is good, the implementation and architecture is not. When you show Form2, you should use the ShowDialog method call, and wait for a DialogResult. If the DialogResult is OK, then you know you should fill your ComboBox. As far as returning the data from Form2, you need to expose a property or field that Form1 can access. Here is a code example:
Form1.cs
namespace CrossFormAccess {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void ShowForm2(object sender, EventArgs e) {
using (Form2 form = new Form2()) {
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK) {
comboBox1.Items.Clear();
comboBox1.Items.AddRange(form.Items);
}
}
}
}
}
Form2.cs
namespace CrossFormAccess {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
public object[] Items;
private void DoWork(object sender, EventArgs e) {
Items = new object[] { "hello", "world" };
DialogResult = DialogResult.OK;
}
}
}
Form1 just has a ComboBox and Button on it where the button shows form2, and Form2 has just a button on it that calls DoWork. You control the DialogResult by setting it when you are ready to close the form. The 'Items' field would be your array or collection of returned data from your datasource.