sqlchild sqlchild - 2 months ago 17
C# Question

calling method on one form from another form, fill combobox on Form1 if a button on Form2 is clicked

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 if OK(Button on Form2) is pressed then the Form1 ComboBox must be filled with values from a SQL SERVER database table.

public partial class FORM1 : Form
{
public void LoadValue()
{
string query = "SELECT FullName FROM Studs ";

SqlCommand cmd = new SqlCommand(query, FORM1conn);

SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
FORM1COMBOBOX.Items.Add(reader.GetString(0));
}
}
}

public partial class FORM2 : Form
{
private void FORM2_OK_Button_Click(object sender, EventArgs e)
{
//HERE I WANT TO CALL THE LOADVALUE() METHOD OF FORM1 ????????
}
}


enter image description here

EDIT:
In form2.cs :

public partial class FORM2 : Form
{

public FORM2(SqlConnection connfromFORM3)
{
Form2Conn = connfromFORM3;
InitializeComponent();
}

private Form1 form1;
public SELECTGROUPHEADDIALOG(FORM1 form1) : this()
{
this.form1 = form1;
}

private void FORM2_OK_Button_Click(object sender, EventArgs e)
{
//HERE I WANT TO CALL THE LOADVALUE() METHOD OF FORM1 ????????
}
}

Answer

Updated

You can try passing Form1 instance in the constructor of Form2

Example:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(this);
        form2.Show();
    }

    internal void TestMethod()
    {
        throw new NotImplementedException();
    }
}

public partial class Form2 : Form
{
    private Form1 form1;

    public Form2()
    {
        InitializeComponent();
    }

    public Form2(Form1 form1)
        : this()
    {
        // TODO: Complete member initialization
        this.form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form1.TestMethod();
    }
}

Updated

try this:

public  FORM2(SqlConnection connfromFORM3, FORM1 form1)
{
    this.form1 = form1;
    Form2Conn = connfromFORM3;
    InitializeComponent();
}
Comments