naouf gyd

naouf gyd

  • NA
  • 15
  • 9.6k

How can I pass data to DataGridView from another form?

Nov 5 2015 3:36 PM

I just want to pass data to DataGridView from another form?

I have 2 windows forms:

  • form1 contains DataGridView1 and button_frm1. The DataGridView have 3 columns and already have some data (6 rows) and DataGridView1 modifiers = Public.

  • form2 contains textBox1 and button_frm2.

Now, when I click button_frm1 form2 appears and next when I click button_frm2 the value in the textBox should be inserted into DataGridView1 in column0 in the selected row. But instead, I got this error:

Index was out of range. Must be non-negative and less than the size of the collection.

Please help me how to insert the textBox value from form2 into DataGridView1 in form1. What steps to follow? Thank you very much in advance.

Here is the code I tried:

Form1:

public partial class Form1 : Form 
{ 
public Form1() 
{ 
InitializeComponent(); 
}
 private void button_frm1_Click(object sender, EventArgs e) 
{ 
Form2 frm2 = new Form2();
frm2.Show(); }  
 }

Form2:

public partial class Form2 : Form 
{ 
public Form2()
 { 
InitializeComponent(); 
} 
private void button_frm2(object sender, EventArgs e)
 { 
Form1 frm1 = new Form1();  
 textBox1.Text= frm1.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
 } 
}

Answers (2)