1
votes

I need some steering in right direction on how to solve this little problem.

I have two forms. On Form1 I have empty dataGridView1 and a button named btnAdd. When user clicks on the button, Form2 is shown (From2.ShowDialog()). On this form2 I have dataGridView2 and a button btn2. Datagridview is bound to an SQL table (it shows id and name columns). When user selects a row in dataGridView and clicks btn2, I need to add that row into dataGridView1. How would I best accomplish this. Thanks for your help.

Here is some code I have.

// I show new form
private void btnAdd_Click(object sender, EventArgs e)
{
  Form2 form2 = new Form2();
  From2.Text = "some title text";
  form2.ShowDialog(this);
}

// In form2 I bind data to dataGridView2 and need to add
// selected item to dataGridView1
public Form2()
{
  InitializeComponent();
  getData();
}

private void getData()
{
  try
  {
    String connectionString = "my connection string";
    SqlConnection connection = new SqlConnection(connectionString);
    DataTable data = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter("my SQL query", connection);
    da.Fill(data);
    dataGridView2.DataSource = data;
  }
  catch (SqlException ex)
  {
    MessageBox.Show(ex.ToString());
  }
}

private void btn2_Click(object sender, EventArgs e)
{
  if (dataGridView2.SelectedCells.Count > 0)
  {
    int i = dataGridView2.SelectedCells[0].RowIndex;
    DataGridViewRow r = dataGridView2.Rows[i];
    //Need to add selected row to dataGridView1
  }
}
2

2 Answers

1
votes

You can use Owner property

Form2 form2 = new Form2(dataGridView1);
        From2.Text = "some title text";
form2.Owner=this;
        form2.ShowDialog(this);

And on form2 ;

((Form1)this.Owner).YOURMETHODTOADDROW(your parameter)

implement YOURMETHODTOADDROW to add row to grid then refresh your grid1

0
votes

You could pass a reference for dataGridView1 to Form2, although this sort of thing can quickly get your code tangled up in knots.

public class Form1 : Form
{
    ...

    private void btnAdd_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(dataGridView1);
        From2.Text = "some title text";

        form2.ShowDialog(this);
    }
}

public class Form2 : Form
{
    private DataGridView form1DataGridView;

    public Form2(DataGridView form1DataGridView)
    {
        InitializeComponent();

        this.form1DataGridView = form1DataGridView;

        getData();
    }

    private void btn2_Click(object sender, EventArgs e)
    {
       // do something with form1DataGridView
    }
}