2
votes

i have 2 forms. form1 contains the datagridview. the second(form2) form contains textboxs. when i click Ok button in form2, the values should get added in datagridview as new row. This is the code i am trying to use to pass the data,but its neither showing error nor result.

Form2

private void btnOk_Click(object sender, EventArgs e)
{ 
  form1.datagridview.Rows.Add("firstname", "lastname", "Success", "Userid", DateTime.Now.ToString());
}
3

3 Answers

3
votes

put this on Form1

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

put this on Form2

    private Form1 form1;

    public Form2(Form1 form1) {
        InitializeComponent();  
        this.form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e) {
        form1.dataGridView1.Columns.Add("FirstName", "First Name");
        form1.dataGridView1.Columns.Add("LastName", "Last Name");
        form1.dataGridView1.Columns.Add("UserId", "Userid");
        form1.dataGridView1.Columns.Add("Success", "Success");

        object[] row = new object[] {"1","Product 1","1000",DateTime.Now.ToString()};

        form1.dataGridView1.Rows.Add(row);
    }

that should do it

and datagridview Modifier should be public

0
votes

You need to add a reference to your form1 somewhere in form2 a somewhat easy way of doing this is to add this to form2 on top

public Form1 form1 {get;set;}

And then when you create your form2 with i suppose something like this from form1

Form2 form2 = new Form2();
form2.ShowDialog();

You add this right after ShowDialog() or before

form2.form1 = this;

Then you can use form1 as a variable inside of form2 to reference to form1

0
votes

This is easiest way I can suggest you:

  • Create public method on Form 2 to add rows to data grid view
  • Create instance of Form 2 on button click and call method of Form 2

Form 1

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var firstName = txtFirstName.Text;
        var lastName = txtLastName.Text;
        var success = txtSuccess.Text;
        var userId = txtUserId.Text;

        var frm2 = new Form2();
        frm2.AddGridViewRows(firstName, lastName, success, userId);
    }

Form 2

    public Form2()
    {
        InitializeComponent();
    }

    public void AddGridViewRows(string firstName, string lastName, string success, string userId)
    {
        // Add rows to grid view.
        dataGridView1.Rows.Add(firstName, lastName, success, userId);

        // Refresh the grid
        dataGridView1.Update();
    }